代码:-
this.shared.refreshPageObeservable().subscribe(data => {
if (data && Object.keys(data).length) {
this.userDetails.fullName = `${data.firstName} ${data.lastName}`;
this.userDetails.lastLogin = `${data.lastLoginDt}`;
} else {
this.userDetails.fullName = '';
this.userDetails.lastLogin = '';
}
});
spec file:-
spyOn(shared, 'refreshPageObeservable').and.returnValue(of({firstName: 'john', lastName: 'doe', lastLoginDt: '12345'}));
fixture.detectChanges();
这段代码覆盖了if语句,但是如何覆盖else部分。
给出一个空对象因此if语句中的Object.keys(data).length
为假因此它进入else块
it('should set fullName and lastLogin to an empty string', () => {
spyOn(shared, 'refreshPageObeservable').and.returnValue(of({}));
// call the function again that is responsible for subscribing to that stream
expect(component.userDetails.fullName).toBe('');
expect(component.userDetails.lastLogin).toBe('');
});