Skip to content

Commit

Permalink
feat(warn): warn if next was called multiple times
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed May 6, 2020
1 parent 5f22d4f commit dce2612
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
23 changes: 23 additions & 0 deletions __tests__/warnings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,27 @@ describe('warnings', () => {
'Alias "/:p/:c" and the original record: "/:p/c" should have the exact same param named "c"'
).toHaveBeenWarned()
})

it('warns if next is called multiple times in one navigation guard', done => {
expect.assertions(3)
let router = createRouter({
history: createMemoryHistory(),
routes: [
{ path: '/', name: 'a', component },
{ path: '/b', name: 'a', component },
],
})

router.beforeEach((to, from, next) => {
next()
expect('').not.toHaveBeenWarned()
next()
expect('called more than once').toHaveBeenWarnedTimes(1)
next()
expect('called more than once').toHaveBeenWarnedTimes(1)
done()
})

router.push('/b')
})
})
26 changes: 23 additions & 3 deletions src/navigationGuards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,12 +127,32 @@ export function guardToPromiseFn(
}

// wrapping with Promise.resolve allows it to work with both async and sync guards
Promise.resolve(guard.call(instance, to, from, next)).catch(err =>
reject(err)
)
Promise.resolve(
guard.call(
instance,
to,
from,
__DEV__ ? canOnlyBeCalledOnce(next, to, from) : next
)
).catch(err => reject(err))
})
}

function canOnlyBeCalledOnce(
next: NavigationGuardCallback,
to: RouteLocationNormalized,
from: RouteLocationNormalized
): NavigationGuardCallback {
let called = 0
return function () {
if (called++ === 1)
warn(
`The "next" callback was called more than once in one navigation guard when going from "${from.fullPath}" to "${to.fullPath}". It should be called exactly one time in each navigation guard. This will fail in production.`
)
if (called === 1) next.apply(null, arguments as any)
}
}

type GuardType = 'beforeRouteEnter' | 'beforeRouteUpdate' | 'beforeRouteLeave'

export function extractComponentsGuards(
Expand Down

0 comments on commit dce2612

Please sign in to comment.