You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 14:05:17