Reputation: 71
I used ngzone and router in component class. My unit testing was working fine but now getting error cannot read toLowerCase() of undefined. Can anyone suggest me how to mock both Ngzone and Router.
Upvotes: 0
Views: 6703
Reputation: 3723
I use TestBed for this :)
Just configure your test module with your component and routes, then get your Router
instance from the test module, and then you spy on Router.navigate
to use your custom mock implementation.
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
let component: YourComponent;
let fixture: ComponentFixture<YourComponent>;
let router: Router;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes([
{ path: "", component: YourComponent },
{ path: "**", redirectTo: "" },
]),
],
declarations: [YourComponent],
providers: [],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
router = TestBed.inject(Router);
jest
.spyOn(router, 'navigate')
.mockImplementation(() => of(true).toPromise());
});
Upvotes: 2