Reputation: 63
I'm trying to test a button that when gets clicked it makes a navigation to my home page, but when I provide the Router class with a Jasmine Spy Object I get a "TypeError: Cannot read property 'root' of undefined".
describe('Error404Component', () =>
{
let component: Error404Component;
let fixture: ComponentFixture<Error404Component>;
const routerSpy = jasmine.createSpyObj('Router', ['navigate']);
beforeEach(async(() =>
{
TestBed.configureTestingModule({
imports: [
AppModule
]
})
.compileComponents();
}));
beforeEach(() =>
{
TestBed.overrideProvider(Router, { useValue: routerSpy });
fixture = TestBed.createComponent(Error404Component);
component = fixture.componentInstance;
fixture.autoDetectChanges();
});
fit('should navigate', fakeAsync(() =>
{
const buttons = fixture.debugElement.queryAll(By.css('.button_link'));
expect(buttons).toBeTruthy();
const homeButton = buttons[0];
(homeButton.nativeElement as HTMLButtonElement).click();
fixture.detectChanges();
tick();
const spy = routerSpy.navigate as jasmine.Spy;
expect(spy.calls.any()).toBeTruthy();
expect(spy.calls.first().args[0][0]).toEqual(HOME_PATH);
}));
});
Upvotes: 1
Views: 3396
Reputation: 8478
You should be providing the router
and all other service injections used in component while configureTestingModule
using TestBed.
describe('Error404Component', () =>
{
class MockRouter {
navigate = jasmine.createSpy('navigate');
}
let component: Error404Component;
let fixture: ComponentFixture<Error404Component>;
let routerSpy;
beforeEach(async(() =>
{
routerSpy= new MockRouter();
TestBed.configureTestingModule({
imports: [
AppModule
],
providers: [{ provide: Router, useValue: routerSpy }],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() =>
{
fixture = TestBed.createComponent(Error404Component);
component = fixture.componentInstance;
fixture.autoDetectChanges();
});
fit('should navigate', fakeAsync(() =>
{
const buttons = fixture.debugElement.queryAll(By.css('.button_link'));
expect(buttons).toBeTruthy();
const homeButton = buttons[0];
(homeButton.nativeElement as HTMLButtonElement).click();
fixture.detectChanges();
tick();
const spy = routerSpy.navigate as jasmine.Spy;
expect(spy.calls.any()).toBeTruthy();
expect(spy.calls.first().args[0][0]).toEqual(HOME_PATH);
}));
});
Upvotes: 0