I'm creating an Angular app and I'm learning unit test and I want to test certain method, but I can't manage to test that the function enters in the if statement. I don't know how to force it. Could you please teach me how to do that? This is the function:
currentRoute(): void {
const router: Router = this.injector.get(Router);
router.events.subscribe((val) => {
if (val instanceof NavigationEnd) {
this.checkMenuLinks(val);
}
});
}
If I run a test-coverage I get al the if statement in red, as not tested. Could you please tell me how to achieve this? Thank you so much.
Most likely you're not triggering router events in your unit test - which is quite normal
You should look up the Angular
RouterTestingModuleThere's some good tutorials on testing the routes themselves, and you'll be looking to trigger the Navigation End event, which should occur during the process. You can add a
jasmine spyto thecheckMenuLinks()method to check if it's been calledOther approaches involved mocking the
Routerservice, and often this is the most efficient approach