angular - 功能单元测试中未涵盖的 if 语句 - Jasmine
问题描述
我正在为某个代码编写 jasmine 测试用例。我已经介绍了组件中的函数,但没有介绍函数中的 if 语句。以下是未涵盖的函数中的 if 语句。
ngOnChanges(changes: SimpleChanges) {
this.branchuserRole = this.userService.getUser().getId();
if (this.data) {
if (this.branchuserRole === this.TEST) {
this.data = this.data.filter(task => task.assignedUser !== null);
this.data = this.data.filter(task => task.assignedRole === this.TEST);
this.summaryListLength = this.data.length;
} else {
this.summaryListLength = this.data.length;
}
整个 if else 部分不在代码覆盖范围内。下面是我试过的代码。
it('should call ngOnChanges function', () => {
const changes: any = '';
spyOn(component, 'ngOnChanges').and.callThrough();
component.ngOnChanges(changes);
expect(component.ngOnChanges).toHaveBeenCalled();
});
it('should set the value of data', () => {
const changes: any = '';
component.ngOnChanges(changes);
component.branchuserRole = TEST;
expect(component.data).toBeTruthy();
expect(component.data).toEqual(component.data.filter(task => task.assignedUser !== null));
expect(component.taskData).toEqual(component.taskData.filter(
task => task.assignedRole === TEST));
expect(component.summaryListLength).toEqual(component.data.length);
});
解决方案
不要忘记您有一个应该返回 branchuserRole 的服务。因此,您必须在 TestBed 中初始化服务,然后您需要对其进行 spy 并返回您想要的值。这就是为什么您不能使用 branchUserRole 跳过 if 语句的原因。现在您只需使用 TEST 初始化 branchUserRole(我不知道什么是测试),但是当您调用 NgOnChanges 时,branchUserRole 的值被覆盖,或者您收到错误,因为服务未初始化。
推荐阅读
- apache - 谁能让我知道htaccess代码中的错误
- python - Django 稍后在命令上提交数据库更改
- mule - 由 Mule Anypoint MQ 发布组件(Mule 4)发布 JSON 有效负载时出现错误(500)
- javascript - 在高图中显示时间序列数据
- laravel - Laravel 7 API 中 Serach 函数的路由
- asp.net - 如何通过文件系统将 Blazor WebAssembly 应用程序发布到 cPanel?
- java - 如何在大括号之间的 Java 文本中使用正则表达式进行选择
- marklogic - 如何知道哪些文档属于集合
- dictionary - wowool词典中stem和normalized_stem的区别
- python - 如何从列表和列表列表中制作字典