vendredi 3 avril 2020

How to test self invoked axios function inside setTimeout with jest

I have hard time to manage with situation where you have to test axios requests in setTimeout. The aim is to achieve 4 times axios calls but the result is just 1:

excerpt from console:

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

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

Here is the code:

in .session.js

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

in /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();
});

Ive tried almost everything including async/await, also that ref: Testing a Recursive polling function with jest and fake timers

but all for nothing

Aucun commentaire:

Enregistrer un commentaire