Skip to content

Commit

Permalink
feat: catch resolve errors (fixes #41) (#53)
Browse files Browse the repository at this point in the history
Co-authored-by: Eduardo San Martin Morote <posva13@gmail.com>
  • Loading branch information
cexbrayat and posva authored Mar 30, 2021
1 parent c31cc03 commit f91dcdc
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
8 changes: 8 additions & 0 deletions __tests__/navigations.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ describe('Navigations', () => {
expect(wrapper.vm.$router.push).toHaveBeenCalledTimes(1)
})

it('can check calls on push even if the route is not declared', async () => {
const wrapper = mount(Test)

wrapper.vm.$router.push({ name: 'hey' })
expect(wrapper.vm.$router.push).toHaveBeenCalledWith({ name: 'hey' })
expect(wrapper.vm.$router.push).toHaveBeenCalledTimes(1)
})

it('can check calls on replace', async () => {
const wrapper = mount(Test)

Expand Down
26 changes: 23 additions & 3 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,14 +74,25 @@ export interface RouterMockOptions extends Partial<RouterOptions> {
* START_LOCATION.
*/
initialLocation?: RouteLocationRaw

/**
* Run in-component guards. Defaults to false
*/
runInComponentGuards?: boolean

/**
* Run per-route guards. Defaults to false
*/
runPerRouteGuards?: boolean

/**
* By default the mock will allow you to push to locations without adding all
* the necessary routes so you can still check if `router.push()` was called
* in a specific scenario
* (https://github.com/posva/vue-router-mock/issues/41). Set this to `true` to
* disable that behavior and throw when `router.push()` fails.
*/
noUndeclaredRoutes?: boolean
}

/**
Expand All @@ -101,7 +112,7 @@ export function createRouterMock(options: RouterMockOptions = {}): RouterMock {
...options,
})

let { runPerRouteGuards, runInComponentGuards } = options
let { runPerRouteGuards, runInComponentGuards, noUndeclaredRoutes } = options
const initialLocation = options.initialLocation || START_LOCATION

const { push, addRoute, replace } = router
Expand Down Expand Up @@ -191,8 +202,17 @@ export function createRouterMock(options: RouterMockOptions = {}): RouterMock {
return pendingNavigation
}

// NOTE: should we trigger a push to reset the internal pending navigation of the router?
router.currentRoute.value = router.resolve(to)
// we try to resolve the navigation
// but catch the error to simplify testing and avoid having to declare
// all the routes in the mock router
try {
// NOTE: should we trigger a push to reset the internal pending navigation of the router?
router.currentRoute.value = router.resolve(to)
} catch (error) {
if (noUndeclaredRoutes) {
throw error
}
}
return Promise.resolve()
}

Expand Down

0 comments on commit f91dcdc

Please sign in to comment.