Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 20 additions & 8 deletions packages/browser-rum-vue/src/domain/error/addVueError.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { initializeVuePlugin } from '../../../test/initializeVuePlugin'
import { addVueError } from './addVueError'

describe('addVueError', () => {
it('reports the error to the SDK with info as first line of component_stack', () => {
it('reports the error to the SDK with info as first line of component_stack', async () => {
const addErrorSpy = jasmine.createSpy()
initializeVuePlugin({ addError: addErrorSpy })
await initializeVuePlugin({ addError: addErrorSpy })

const error = new Error('something broke')
addVueError(error, null, 'mounted hook')
Expand All @@ -21,9 +21,9 @@ describe('addVueError', () => {
)
})

it('includes component hierarchy in component_stack when instance is provided', () => {
it('includes component hierarchy in component_stack when instance is provided', async () => {
const addErrorSpy = jasmine.createSpy()
initializeVuePlugin({ addError: addErrorSpy })
await initializeVuePlugin({ addError: addErrorSpy })

// Build a mock instance chain without @vue/test-utils to avoid
// Object.fromEntries compatibility issues on older browsers
Expand All @@ -42,17 +42,17 @@ describe('addVueError', () => {
expect(componentStack).toContain('at <ParentComponent>')
})

it('handles empty info gracefully', () => {
it('handles empty info gracefully', async () => {
const addErrorSpy = jasmine.createSpy()
initializeVuePlugin({ addError: addErrorSpy })
await initializeVuePlugin({ addError: addErrorSpy })
addVueError(new Error('oops'), null, '')
expect(addErrorSpy).toHaveBeenCalledTimes(1)
expect(addErrorSpy.calls.mostRecent().args[0].componentStack).toBeUndefined()
})

it('should merge dd_context from the original error with vue error context', () => {
it('should merge dd_context from the original error with vue error context', async () => {
const addErrorSpy = jasmine.createSpy()
initializeVuePlugin({ addError: addErrorSpy })
await initializeVuePlugin({ addError: addErrorSpy })
const originalError = new Error('error message')
;(originalError as any).dd_context = { component: 'Menu', param: 123 }

Expand All @@ -64,4 +64,16 @@ describe('addVueError', () => {
param: 123,
})
})

it('does not throw when reading dd_context throws', async () => {
const addErrorSpy = jasmine.createSpy()
await initializeVuePlugin({ addError: addErrorSpy })
const error = new Error('oops')
Object.defineProperty(error, 'dd_context', {
get() {
throw new Error('getter failed')
},
})
expect(() => addVueError(error, null, '')).not.toThrow()
})
})
25 changes: 12 additions & 13 deletions packages/browser-rum-vue/src/domain/error/addVueError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { ComponentInternalInstance, ComponentPublicInstance } from 'vue'
import { clocksNow } from '@datadog/js-core/time'
import { callMonitored } from '@datadog/js-core/monitor'
import { createHandlingStack } from '@datadog/browser-core'
import { onRumStart } from '../vuePlugin'
import { addVueErrorWhenReady } from '../vuePlugin'

/**
* Add a Vue error to the RUM session.
Expand All @@ -21,18 +21,17 @@ import { onRumStart } from '../vuePlugin'
export function addVueError(error: unknown, instance: ComponentPublicInstance | null, info: string) {
const handlingStack = createHandlingStack('vue error')
const startClocks = clocksNow()
onRumStart((addError) => {
callMonitored(() => {
addError({
error,
handlingStack,
componentStack: buildComponentStack(instance, info),
startClocks,
context: {
...(typeof error === 'object' && error !== null ? (error as { dd_context?: object }).dd_context : undefined),
framework: 'vue',
},
})
callMonitored(() => {
// Build the whole payload now so the buffered error does not retain the component instance
addVueErrorWhenReady({
error,
Comment thread
gogusarov marked this conversation as resolved.
Resolved
handlingStack,
componentStack: buildComponentStack(instance, info),
startClocks,
context: {
...(typeof error === 'object' && error !== null ? (error as { dd_context?: object }).dd_context : undefined),
framework: 'vue',
},
})
})
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,33 +1,5 @@
import { display } from '@datadog/browser-core'
import type { RouteLocationMatched } from 'vue-router'
import { initializeVuePlugin } from '../../../test/initializeVuePlugin'
import { startVueRouterView, computeViewName } from './startVueRouterView'

describe('startVueRouterView', () => {
it('starts a new view with the computed view name', () => {
const startViewSpy = jasmine.createSpy()
initializeVuePlugin({
configuration: { router: true },
publicApi: { startView: startViewSpy },
})

startVueRouterView(
[{ path: '/' }, { path: 'user' }, { path: ':id' }] as unknown as RouteLocationMatched[],
'/user/1'
)

expect(startViewSpy).toHaveBeenCalledOnceWith('/user/:id')
})

it('warns if router: true is missing from plugin config', () => {
const warnSpy = spyOn(display, 'warn')
initializeVuePlugin({ configuration: {} })
startVueRouterView([], '/')
expect(warnSpy).toHaveBeenCalledOnceWith(
'`router: true` is missing from the vue plugin configuration, the view will not be tracked.'
)
})
})
import { computeViewName } from './startVueRouterView'

describe('computeViewName', () => {
it('returns an empty string if there is no route match', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,4 @@
import { display } from '@datadog/browser-core'
import type { RouteLocationMatched } from 'vue-router'
import { onRumInit } from '../vuePlugin'

export function startVueRouterView(matched: RouteLocationMatched[], path: string) {
onRumInit((configuration, rumPublicApi) => {
if (!configuration.router) {
display.warn('`router: true` is missing from the vue plugin configuration, the view will not be tracked.')
return
}
rumPublicApi.startView(computeViewName(matched, path))
})
}

export function computeViewName(matched: RouteLocationMatched[], path: string): string {
if (!matched || matched.length === 0) {
Expand Down
12 changes: 6 additions & 6 deletions packages/browser-rum-vue/src/domain/router/vueRouter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { createRouter } from './vueRouter'
describe('createRouter (wrapped)', () => {
it('calls startView on navigation', (done) => {
const startViewSpy = jasmine.createSpy()
initializeVuePlugin({
void initializeVuePlugin({
configuration: { router: true },
publicApi: { startView: startViewSpy },
})
Expand Down Expand Up @@ -33,7 +33,7 @@ describe('createRouter (wrapped)', () => {

it('does not call startView when navigation is duplicated', (done) => {
const startViewSpy = jasmine.createSpy()
initializeVuePlugin({
void initializeVuePlugin({
configuration: { router: true },
publicApi: { startView: startViewSpy },
})
Expand All @@ -58,7 +58,7 @@ describe('createRouter (wrapped)', () => {

it('does not call startView when only query params change', (done) => {
const startViewSpy = jasmine.createSpy()
initializeVuePlugin({
void initializeVuePlugin({
configuration: { router: true },
publicApi: { startView: startViewSpy },
})
Expand All @@ -83,7 +83,7 @@ describe('createRouter (wrapped)', () => {

it('calls startView on initial navigation to /', (done) => {
const startViewSpy = jasmine.createSpy()
initializeVuePlugin({
void initializeVuePlugin({
configuration: { router: true },
publicApi: { startView: startViewSpy },
})
Expand All @@ -104,7 +104,7 @@ describe('createRouter (wrapped)', () => {

it('substitutes catch-all pattern with the actual path', (done) => {
const startViewSpy = jasmine.createSpy()
initializeVuePlugin({
void initializeVuePlugin({
configuration: { router: true },
publicApi: { startView: startViewSpy },
})
Expand All @@ -128,7 +128,7 @@ describe('createRouter (wrapped)', () => {

it('does not call startView when navigation is blocked', (done) => {
const startViewSpy = jasmine.createSpy()
initializeVuePlugin({
void initializeVuePlugin({
configuration: { router: true },
publicApi: { startView: startViewSpy },
})
Expand Down
6 changes: 4 additions & 2 deletions packages/browser-rum-vue/src/domain/router/vueRouter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createRouter as originalCreateRouter } from 'vue-router'
import type { RouterOptions, Router } from 'vue-router'
import { startVueRouterView } from './startVueRouterView'
import { startVueViewWhenReady } from '../vuePlugin'
import { computeViewName } from './startVueRouterView'

export function createRouter(options: RouterOptions): Router {
const router = originalCreateRouter(options)
Expand All @@ -19,7 +20,8 @@ export function createRouter(options: RouterOptions): Router {
if (from.matched.length > 0 && to.path === from.path) {
return
}
startVueRouterView(to.matched, to.path)
// Compute the view name now so the buffered view does not retain route records
startVueViewWhenReady(computeViewName(to.matched, to.path))
})

return router
Expand Down
96 changes: 79 additions & 17 deletions packages/browser-rum-vue/src/domain/vuePlugin.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,24 @@
import { version as vueVersion } from 'vue'
import { toMajorVersionIntegration } from '@datadog/browser-core'
import { display, toMajorVersionIntegration } from '@datadog/browser-core'
import type { RumInitConfiguration, RumPluginOnInitOptions, RumPublicApi } from '@datadog/browser-rum-core'
import { registerCleanupTask } from '../../../browser-core/test'
import { onRumInit, vuePlugin, resetVuePlugin } from './vuePlugin'
import { registerCleanupTask, waitNextMicrotask } from '../../../browser-core/test'
import type { VuePluginConfiguration, VueErrorPayload } from './vuePlugin'
import { vuePlugin, resetVuePlugin, startVueViewWhenReady, addVueErrorWhenReady } from './vuePlugin'

const PUBLIC_API = {} as RumPublicApi

function initPlugin(configuration: VuePluginConfiguration, startView = jasmine.createSpy()) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- onInit never returns a promise for this plugin
vuePlugin(configuration).onInit({
publicApi: { startView } as unknown as RumPublicApi,
initConfiguration: {} as RumInitConfiguration,
} as RumPluginOnInitOptions)
return startView
}

function error(message: string) {
return { error: new Error(message) } as VueErrorPayload
}
const INIT_CONFIGURATION = {} as RumInitConfiguration

describe('vuePlugin', () => {
Expand All @@ -16,22 +30,70 @@ describe('vuePlugin', () => {
expect(vuePlugin()).toEqual(jasmine.objectContaining({ name: 'vue' }))
})

it('calls callbacks registered with onRumInit during onInit', () => {
const spy = jasmine.createSpy()
const config = {}
onRumInit(spy)
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- onInit never returns a promise for this plugin
vuePlugin(config).onInit({ publicApi: PUBLIC_API, initConfiguration: INIT_CONFIGURATION } as RumPluginOnInitOptions)
expect(spy).toHaveBeenCalledOnceWith(config, PUBLIC_API)
it('replays views notified before onInit, in order', async () => {
startVueViewWhenReady('/a')
startVueViewWhenReady('/b')
const startView = initPlugin({ router: true })
await waitNextMicrotask()
expect(startView.calls.allArgs()).toEqual([['/a'], ['/b']])
})

it('calls callbacks immediately if onInit was already invoked', () => {
const spy = jasmine.createSpy()
const config = {}
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- onInit never returns a promise for this plugin
vuePlugin(config).onInit({ publicApi: PUBLIC_API, initConfiguration: INIT_CONFIGURATION } as RumPluginOnInitOptions)
onRumInit(spy)
expect(spy).toHaveBeenCalledOnceWith(config, PUBLIC_API)
it('starts views notified after onInit', async () => {
const startView = initPlugin({ router: true })
await waitNextMicrotask()
startVueViewWhenReady('/a')
expect(startView).toHaveBeenCalledOnceWith('/a')
})

it('starts each view once when onInit is called several times', async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion

if we remove viewSubscription?.unsubscribe() line from vuePlugin this test will still pass

let's assign first initPlugin call to a variable as well and check that
expect(firstStartView).not.toHaveBeenCalled()

const firstStartView = initPlugin({ router: true })
const startView = initPlugin({ router: true })
await waitNextMicrotask()
startVueViewWhenReady('/a')
expect(firstStartView).not.toHaveBeenCalled()
expect(startView).toHaveBeenCalledOnceWith('/a')
})

it('warns and does not start views when router is not enabled', async () => {
const warnSpy = spyOn(display, 'warn')
startVueViewWhenReady('/a')
const startView = initPlugin({})
await waitNextMicrotask()
expect(startView).not.toHaveBeenCalled()
expect(warnSpy).toHaveBeenCalledOnceWith(
'`router: true` is missing from the vue plugin configuration, the view will not be tracked.'
)
})

it('keeps only the 500 most recent views before onInit', async () => {
for (let i = 0; i < 501; i++) {
startVueViewWhenReady(`/${i}`)
}
const startView = initPlugin({ router: true })
await waitNextMicrotask()
expect(startView).toHaveBeenCalledTimes(500)
expect(startView.calls.first().args[0]).toBe('/1')
})

it('replays errors notified before onRumStart, then reports new ones', async () => {
const addError = jasmine.createSpy()
const first = error('first')
addVueErrorWhenReady(first)
vuePlugin().onRumStart({ addError })
await waitNextMicrotask()
const second = error('second')
addVueErrorWhenReady(second)
expect(addError.calls.allArgs()).toEqual([[first], [second]])
})

it('keeps only the 500 most recent errors before onRumStart', async () => {
for (let i = 0; i < 501; i++) {
addVueErrorWhenReady(error(String(i)))
}
const addError = jasmine.createSpy()
vuePlugin().onRumStart({ addError })
await waitNextMicrotask()
expect(addError).toHaveBeenCalledTimes(500)
})

it('sets trackViewsManually when router is true', () => {
Expand Down
Loading
Loading