[英]Angular - Router unit testing with testing module and RouterMock
I've read several questions about how to unit test routing. 我已经阅读了有关如何对路由进行单元测试的几个问题。 But nothing fits my case really. 但确实没有什么适合我的情况。 I have a navbar-comp. 我有一个navbar-comp。 with several [routerLink]=[...]
And when I simulate a click event. 和几个[routerLink]=[...]
并且当我模拟click事件时。 I want for instance to call expect(router.navigate).toHaveBeenCalledWith(*path*);
例如,我想调用expect(router.navigate).toHaveBeenCalledWith(*path*);
But I am already failing on the test setup: It throws me everytime a: cannot find root of undefined
. 但是我已经在测试设置上失败了:每次a: cannot find root of undefined
让我失望。
describe('NavbarComponent', () => {
let component: NavbarComponent;
let fixture: ComponentFixture<NavbarComponent>;
const router: Router = jasmine.createSpyObj('Router', ['navigate']);
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
NgbModule.forRoot(),
RouterTestingModule
],
providers: [
{provide: Router, useValue: router}
],
declarations: [
NavbarComponent,
]
})
.compileComponents();
}));
it('should navigate on click - home', () => {
(<jasmine.Spy>router.navigate).and.stub();
const debugElm = fixture.debugElement.nativeElement.querySelector('#navLogo');
debugElm.click();
expect(router.navigate).toHaveBeenCalledWith(['/stories']);
});
When I delete the RoutingTestingModule
import then it throws me: Cannot bind to routerLink
- which I actually need to test. 当我删除RoutingTestingModule
导入时,它会抛出我: Cannot bind to routerLink
我实际上需要对其进行测试。 Really frustrating... Does anyone has a solution for this? 真令人沮丧...有人对此有解决方案吗?
The RouterTestingModule already provides a mock Router instance so there is no need to provide one explicitly in the test. RouterTestingModule已经提供了一个模拟Router实例,因此无需在测试中明确提供一个实例。 Try something like that: 尝试这样的事情:
describe('NavbarComponent', () => {
let component: NavbarComponent;
let fixture: ComponentFixture<NavbarComponent>;
let navigateSpy: Spy;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
NgbModule.forRoot(),
RouterTestingModule
],
declarations: [
NavbarComponent,
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(NavbarComponent);
component = fixture.componentInstance;
navigateSpy = spyOn(TestBed.get(Router), 'navigate'); // <= init spy
});
it('should navigate on click - home', () => {
const debugElm = fixture.debugElement.nativeElement.querySelector('#navLogo');
debugElm.click();
expect(navigateSpy).toHaveBeenCalledWith(['/stories']); // <= check spy
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.