angularunit-testingjasminekarma-jasminespecs

How to mock router in angular jasmine spec


I am new to writing test specs using jasmine. I have a condition in ngOnInit() something like, router.url.includes(some string). The default spec test case which checks component to be truthy is getting failed saying TypeError: Cannot find includes of undefined. Is there any way to spy or mock includes?


Solution

  • You can use RouterTestingModule to mock the angular router.

    Just import the angular router as below.

    import { RouterTestingModule } from '@angular/router/testing';
    import { ActivatedRoute, Router } from '@angular/router';
    

    And add it to the imports array of NgModule

    
    TestBed.configureTestingModule({
        declarations: [
            someComponent
        ],
        imports: [
            RouterTestingModule.withRoutes([]),
        ],
        providers: [someProvider],
    }).compileComponents
    
    

    Then you can inject the Router as follows and use it for testing

    it('should Navigate', () => {
        const actiavtedRoute = TestBed.inject(ActivatedRoute);
        const router = TestBed.inject(Router);
    })