[英]unit test a function with router navigateByUrl using karma jasmine
I am trying to unit test the following function which has router navigateByUrl, but couldnt execute.then block我正在尝试对以下具有路由器 navigateByUrl 的 function 进行单元测试,但无法执行。然后阻止
.ts code: .ts 代码:
back(){
this.router.navigateByUrl('/routepath').then(() => {
Object.keys(['column']).forEach((obj, val) => {
myService.setDefaultGroup();
});
});
}
Here is what i have tried in my spec.ts这是我在我的 spec.ts 中尝试过的
class MockRouter {
navigateByUrl = () => {
return {
then: () => {}
}
}
}
configureTestSuite(() => {
TestBed.configureTestingModule({
providers: [{ provide: Router, useClass: MockRouter } ]
})
});
describe('should call back', () => {
it('should call Router.navigateByUrl', inject([Router], (router: Router) => {
const spy = spyOn(router, 'navigateByUrl');
component.back();
}));
});
What is the output received收到的output是什么
TypeError: Cannot read property 'then' of undefined类型错误:无法读取未定义的属性“then”
Expected:预期的:
Test case should execute测试用例应该执行
I am using karma and jasmine to unit test this.我正在使用业力和 jasmine 对此进行单元测试。 Help me out if i am missing anything
如果我遗漏了什么,请帮助我
When you spyOn
a method, it stubs it out to return undefined.当您
spyOn
一个方法时,它会将其存根以返回未定义。
You need to use .and.callThrough()
to not lose implementation details.您需要使用
.and.callThrough()
以免丢失实现细节。
Try:尝试:
describe('should call back', () => {
it('should call Router.navigateByUrl', inject([Router], (router: Router) => {
const spy = spyOn(router, 'navigateByUrl').and.callThrough();
component.back();
}));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.