【发布时间】:2021-03-23 23:44:53
【问题描述】:
我正在使用 jasmine 在 Angular 中学习单元测试。我有一个组件,其中ngOnInit() 方法具有某些服务调用。下面是我的ngOnInit() 方法:
ngOnInit() {
this.componentInteractionService.resetCurrentMenu();
this.router.paramMap.subscribe(params => {
this.currentContentUrl = params.get("currentContentUrl");
let tmp = params.get("contentTitle");
this.contentSubstitle = params.get("contentSubtitle");
if (tmp == undefined) {
let url = this.currentContentUrl;
this.contentTitle = url.substring(url.lastIndexOf("/") + 1, url.length);
}
else {
this.contentTitle = tmp;
}
});
}
那么我应该如何测试才能覆盖ngOnInit() 方法的所有行?我的意思是我需要完整的代码覆盖率。
在我的spec.ts:
it('should call all methods in ngOnInit', () => {
component.ngOnInit();
.......
.......
});
component.ngOnInit();之后应该写什么?请帮忙。我可以测试第一行是:
this.componentInteractionService.resetCurrentMenu();
但是如何测试其余的行?
【问题讨论】:
-
您可以模拟
paramMap以返回您需要的值。返回一个值,使if块被覆盖,您可以断言contentTitle、contentSubtitle和currentContentUrl,else块也是如此。 stackoverflow.com/questions/45917883/… 这就是你模拟 paramMap 的方式,对你来说,你也需要模拟params.get。 -
@AliF50 if 条件要求 tmp 未定义....但 tmp 是一个 let 变量。如何将 tmp 设置为未定义?
-
但是
tmp是从params.get('contentTitle')设置的,您应该在测试中控制它。 -
@DhritimanTamuliSaikia:你介意让我知道我的答案中的任何 cmets 吗?
-
@ShashankVivek 抱歉回复晚了...但发生的事情是我现在被要求使用 Jest 进行测试...所以我在处理 Jest 时面临其他几个问题...没有检查您的代码是否正常工作。
标签: angular unit-testing jasmine karma-jasmine