Skip to content

Error when writing tests for the auth guard: The '_Router' token injection failed. 'inject()' function must be called from an injection context #690

@thelongshot

Description

@thelongshot

When we rewrote the guard in the 'new' way, we found that one of our tests doesn't work anymore. It is mainly because of this line at the end of the guard. It mostly follows the code in the documentation.

// If not valid, redirect to the welcome screen
return inject(Router).createUrlTree(['/welcome']);

The test looks like this:

const fakeUrlTree = { toString: () => '/welcome' } as unknown as UrlTree;

it('should redirect when required role not present', async() => {
const activatedRoute = jasmine.createSpyObj<ActivatedRouteSnapshot>('activatedRoute', {}, { data: { roles: [ Role.Admin ] }} )
const routerState = jasmine.createSpyObj<RouterStateSnapshot>('routeState', {}, {url: '/test'})

await Testbed.runInInjectionContext(async () => {
expect await guard(activatedRoute, routerState)).toBe(fakeUrlTree);
})
})

Unfortunately, this fails with "The '_Router' token injection failed. 'inject()' function must be called from an injection context". Testbed.runInInjectionContext is supposed to take care of that, but seems to have issues with the async method of the guard. I've tried the call with and without the await before guard, with no difference. I'm kinda baffled at what is going on here and how to get this test running again.

I had looked at the test in gitlab, but that doesn't test the logic of the guard. Just a mock guard and checking the inputs and outputs. Is there some way to test when it falls out?

Metadata

Metadata

Assignees

No one assigned

    Labels

    need-informationMore information is neededquestionThis issue is a question.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions