我正在为以下代码块编写测试用例:
someFn() {
if (this.loginStatus === '1') {
this.router.navigate(['/login']);
}
}
在我的规范文件中:
import { Router } from '@angular/router'
describe('MyComponent', () => {
let routerStub;
beforeEach(async(() => {
routerStub = {
navigate: jasmine.createSpy('navigate'),
};
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [
{ provide: Router, useValue: routerStub },
],
}).compileComponents()
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.autoDetectChanges();
});
it('navigate to login', () => {
component.loginStatus = '1';
component.someFn();
expect(routerStub.navigate).toHaveBeenCalledWith(['/login']);
});
})
上面给了我错误: Expected spy navigate to have been called with [ [ '/login' ] ] 但它从未被调用过。
我该如何解决这个问题?我已经尝试了很多来自 SO 的解决方案,但似乎没有什么对我有用。
代码是用 Angular 7 编写的,我使用的是 jasmine+karma。