如何在Angular中正确测试setInterval()内的语句?
问题:测试setInterval中
getAuthInfo的调用覆盖率 业务代码
public async authenticate(username: string, password: string) { const authenticationResponse = await this.dataProvider.authenticate(username, password); if (authenticationResponse.result.code == 0) { //start interval for periodically checking authentication info this._authInfoIntervalId = setInterval(() => { this.getAuthInfo(); }, 2000); }
问题说明
单元测试中,唯独this.getAuthInfo()这一行未被覆盖,尝试用jasmine.createSpy相关方法但没效果,求正确的测试实现方式。
失败的测试尝试
it('should test interval somehow', () => { const intervalCallback = jasmine.createSpy("getAuthInfo"); jasmine.clock().install(); service.authenticate('username', 'password'); jasmine.clock().tick(2001); expect(intervalCallback).toHaveBeenCalled(); })
测试失败提示:AuthenticationService should test interval somehow FAILED Expected spy getAuthInfo to have been called.
正确解决方案
需要先对dataProvider.authenticate进行Spy,让它返回符合条件的响应(使代码能进入interval逻辑分支),同时Spy目标服务的getAuthInfo方法,再配合异步处理和Jasmine时钟推进:
it('should test interval somehow', async () => { const intervalCallback = spyOn(service, 'getAuthInfo'); spyOn(dataProvider, 'authenticate').and.returnValue(Promise.resolve(authenticateMockResponse)); jasmine.clock().install(); await service.authenticate('username', 'password'); jasmine.clock().tick(2001); expect(intervalCallback).toHaveBeenCalled(); });
内容的提问来源于stack exchange,提问作者Raadush
相关产品推荐
相关产品推荐

