如何用玩笑测试setTimeout内部的自调用axios函数

时间:2020-04-03 14:05:09

标签: asynchronous testing jestjs axios settimeout

我很难处理必须在setTimeout中测试axios请求的情况。目的是实现4次axios调用,但结果仅为1:

从控制台摘录:

 expect(jest.fn()).toHaveBeenCalledTimes(4)

 Expected mock function to have been called four times, but it was called one time.

代码如下:

session.js中:

import axios from 'axios';

export const HeartBeat = {
  beat: function() {
    setTimeout(() => this.callAjax(), 1000);
  },
  callAjax: function() {
    const self = this;
    axios({ method: 'PATCH', data: { state: 'keep_alive' } }).then(() => self.beat());
  },
};

session.spec.js中:

import axios from 'axios';
import Session, {HeartBeat} from 'bundles/components/Header/session';

jest.mock('axios');
jest.useFakeTimers();

it("should call heartbeat multiple times", done => {
   axios.mockImplementationOnce(() => Promise.resolve());

   HeartBeat.beat();
   jest.runTimersToTime(3001);

   expect(axios).toHaveBeenCalledTimes(4);
   done();
});

我已经尝试了几乎所有内容,包括异步/等待,以及参考:Testing a Recursive polling function with jest and fake timers

但一无所获

0 个答案:

没有答案