我很难处理必须在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
但一无所获