--- /dev/null
+/**
+ * @jest-environment jsdom
+ */
+import { createDom, newRouter as createRouter } from '../utils'
+import { mount } from '@vue/test-utils'
+import { inject } from 'vue'
+import { mockWarn } from 'jest-mock-warn'
+import type { Router } from '../../src'
+
+describe('inject() within navigation guards', () => {
+ mockWarn()
+ beforeAll(() => {
+ createDom()
+ })
+
+ const PageComponent = {
+ template: `<div>Page</div>`,
+ }
+
+ function factory(router: Router) {
+ return mount(
+ {
+ template: `<RouterView />`,
+ },
+ {
+ global: {
+ plugins: [router],
+ provide: {
+ test: 'hello',
+ },
+ },
+ }
+ )
+ }
+
+ const globalGuards = ['beforeEach', 'beforeResolve', 'afterEach'] as const
+
+ for (const guardName of globalGuards) {
+ it(`router.${guardName}()`, async () => {
+ expect.assertions(1)
+ const router = createRouter({
+ routes: [{ path: '/', component: PageComponent }],
+ })
+ router[guardName](() => {
+ expect(inject('test')).toBe('hello')
+ })
+ factory(router)
+ await router.isReady()
+ })
+ }
+})
RouteLocationOptions,
MatcherLocationRaw,
RouteParams,
+ NavigationGuardReturn,
} from './types'
import { RouterHistory, HistoryState, NavigationType } from './history/common'
import {
return error ? Promise.reject(error) : Promise.resolve()
}
+ function runWithContext<T>(fn: () => T): T {
+ const app: App | undefined = installedApps.values().next().value
+ // support Vue < 3.3
+ return app && typeof app.runWithContext === 'function'
+ ? app.runWithContext(fn)
+ : fn()
+ }
+
// TODO: refactor the whole before guards by internally using router.beforeEach
function navigate(
): void {
// navigation is confirmed, call afterGuards
// TODO: wrap with error handlers
- for (const guard of afterGuards.list()) guard(to, from, failure)
+ for (const guard of afterGuards.list()) {
+ runWithContext(() => guard(to, from, failure))
+ }
}
/**
},
}
- return router
-}
+ // TODO: type this as NavigationGuardReturn or similar instead of any
+ function runGuardQueue(guards: Lazy<any>[]): Promise<any> {
+ return guards.reduce(
+ (promise, guard) => promise.then(() => runWithContext(guard)),
+ Promise.resolve()
+ )
+ }
-function runGuardQueue(guards: Lazy<any>[]): Promise<void> {
- return guards.reduce(
- (promise, guard) => promise.then(() => guard()),
- Promise.resolve()
- )
+ return router
}
function extractChangingRecords(