how to retrieve response data when unit testing async redux action

Viewed 48

I'm trying to make this test, test the getImages action function. I'm getting this error

● should getImages from action function › should getImages from action function

expect(received).toEqual(expected) // deep equality

Expected: {"data": {}, "type": "GET_IMAGES"}
Received: [Function anonymous]

ideally I want to pass in the response data, in the data object. How would I successfully do this to make the test pass?

imageActions

import { GET_IMAGES, POST_COMMENT, DELETE_IMAGE, UPLOAD_IMAGE } from './types';
import Axios from '../Axios';

export const getImages = () => {
  return dispatch => {
    return Axios.get('/images/uploads').then(response => {
      const data = response.data;
      dispatch({
        type: GET_IMAGES,
        data
      });
    });
  };
};

imageActions.test.js

import React from 'react';
import { shallow, mount } from 'enzyme';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { getImages } from './imageActions';
import { GET_IMAGES } from './types';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('should getImages from action function ', () => {
  it('should getImages from action function', () => {
    const expected = {
      type: GET_IMAGES,
      data: {}
    };
    const actual = getImages();
    expect(actual).toEqual(expected);
  });
});
1 Answers

Since you are using redux-mock-store, you should take a look at the examples of how to test async actions.

You will also have to mock the ajax request you are doing through your Axios module. As an example, I will use jest mock to mock the Axios module.

The code would look like:

import React from 'react';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { getImages } from './imageActions';
import { GET_IMAGES } from './types';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

// Mocking the Axios get method so that it returns something in data
jest.mock('../Axios', () => ({
    get: jest.fn(() => Promise.resolve({ data: ['image1', 'image2'] }))
}));

describe('should getImages from action function ', () => {
    it('should getImages from action function', () => {
        const expected = {
            type: GET_IMAGES,
            data: ['image1', 'image2']
        };

        // Initialize mockstore with empty state
        const store = mockStore({});

        // Return the promise returned by store.dispatch so that the test waits until it's resolved.
        return store.dispatch(getImages()).then(() => {
            // Get the actions that have been dispatched
            const actions = store.getActions();

            // Check that the only action has the expected values.
            expect(actions[0]).toEqual(expected);
        });
    });
});
Related