dimanche 27 janvier 2019

Jest mock module resolve with variable value

Assuming I have a module which returns a promise. I want to mock different outcomes of this promise to test the function where this module is part of. I mock the module like this:

jest.mock('../request', () => {
    return () => new Promise((resolve, reject) => {
        return resolve({
            response: { ok: true }
        });
    });
});

My first test is running

test('The function resolves', () => {
const initialState = { apiData: getState('postData', {}, 'ready', 'POST') };
const store: any = mockStore(initialState);
return expect(performApiRequest('postData/', {}, { data: 'json' }) (dispatch, () => store.getState())).resolves.toBeUndefined();
});

The problem is now with testing an other function where the value that resolves is supposed to be different, for instance {response: { ok: false } }.

I already tried different things. First wrapping the mock in a function and give the response as an argument. --> fails for mocks can't take out of scope variables.

I tried to call jest.doMock within the test but this does not trigger the request correctly.

I tried to do

`
    const mockResponse = jest.fn();
    jest.mock('../request', () => {
        return () => new Promise((resolve, reject) => {
            return resolve({
                mockResponse
            });
        });
     });`

And then call mockResponse.mockReturnValueOnce(value).

No success yet. Anybody sees a way out?

Aucun commentaire:

Enregistrer un commentaire