我正在为某个代码编写茉莉花测试用例。我已经介绍了组件中的功能,但未介绍功能中的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);
});
答案 0 :(得分:1)
需要在调用branchuserRole
之前设置data
和ngOnChanges
it('should set the value of data', () => {
const changes: any = '';
component.branchuserRole = TEST;
component.data= []; // should not be null
component.ngOnChanges(changes);
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);
});
答案 1 :(得分:1)
别忘了您有一个应该返回branchuserRole的服务。因此,您必须在TestBed中初始化服务,然后需要对其进行监视并返回所需的值。这就是为什么您不能使用branchUserRole跳过if语句的原因。现在,您只是使用TEST初始化了branchUserRole(我不知道是什么测试员),但是当您调用NgOnChanges时,branchUserRole的值将被覆盖,或者由于未初始化服务而收到错误消息。