我有一个对ngOninit进行get调用的组件
ngOnInit(): void {
this.setMemberRoles();
}
public setMemberRoles(): void {
this.teamService.getMemberRoles().subscribe((response: ICreatedByRole) => {
this.memberRoles = response;
});
}
我想为此编写测试用例:
it('should set member roles in variable member roles', async(() => {
let response: ICreatedByRole[] = [];
spyOn(teamServiceStub, 'getMemberRoles').and.returnValue(of(response));
component.setMemberRoles();
fixture.detectChanges();
expect(component.memberRoles).toEqual(response);
}));
我已经尝试过,但是会引发错误
<spyOn> : could not find an object to spy upon for getMemberRoles()
Usage: spyOn(<object>, <methodName>)
有什么主意吗?
答案 0 :(得分:1)
模拟teamService。
class MockTeamService {
getMemberRoles {
return 'fake response'
}
}
将此MockTeamService注入提供商中。
{provider: TeamService, useClass: MockTeamService}
获取注入的服务。
teamService = TestBed.get(TeamService);
然后监听:
const memberSpy = spyOn(teamService,
'getMemberRoles').and.returnValue(of(response));