1

I am using Jest and moxios to write a test for my async function:

export function getData(id) {
  return dispatch => {
    return axios({
      method: "get",
      url: `${'url'}/id`
    })
      .then(response => {
        dispatch(setData(response.data));
      })
      .catch(() => alert('Could not fetch data');
  };
}

Test:

import configureMockStore from "redux-mock-store";
import thunk from "redux-thunk";
import moxios from "moxios";
import getData from '../redux/getData';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const store = mockStore({});

describe('Test fetch data', () => {
  beforeEach(function() {
    moxios.install();
    store.clearActions();
  });
  afterEach(function() {
    moxios.uninstall();
  });
  it('should fetch data and set it', () => {
         const data = [{ name: 'John', profession: 'developer'}];
         moxios.wait(() => {
         const request = moxios.requests.mostRecent();
         request.respondWith({
           status: 200,
           response: data
         });
        const expectedActions = [setData(data)];
        return store.dispatch(getData()).then(() => {
        expect(store.getActions()).toEqual(expectedActions);
      });
    });
  })
})

My test is passing, but when I check the code coverage report generated by Jest, it shows that the then block of getData was not covered/called. How can I fix this?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
darKnight
  • 5,651
  • 13
  • 47
  • 87
  • Did it gave you an error or nothing at all? By the way, [check this question](https://stackoverflow.com/questions/53004395/how-to-test-async-function-making-use-of-moxios) it may help you :) – reymon359 May 09 '20 at 14:18

1 Answers1

0

moxios.wait return Promise your test function return before running except functions.

you need to use done callback in your test function

it('should fetch data and set it', (done) => {
    const data = [{
        name: 'John',
        profession: 'developer'
    }];
    moxios.wait(() => {
        const request = moxios.requests.mostRecent();
        request.respondWith({
            status: 200,
            response: data
        });
        const expectedActions = [setData(data)];
        store.dispatch(getData()).then(() => {
            expect(store.getActions()).toEqual(expectedActions);
            done();
        });
    });
});
Ali Faris
  • 17,754
  • 10
  • 45
  • 70