Home > database >  How can I test that a function was called inside an if statement in jasmine-karma
How can I test that a function was called inside an if statement in jasmine-karma

Time:11-05

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.

CodePudding user response:

Most likely you're not triggering router events in your unit test - which is quite normal

You should look up the Angular RouterTestingModule

There'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 spy to the checkMenuLinks() method to check if it's been called

Other approaches involved mocking the Router service, and often this is the most efficient approach

  • Related