简体   繁体   中英

how to write test cases for redux async actions using axios?

Following is a sample async action creator.

export const GET_ANALYSIS = 'GET_ANALYSIS';
export function getAllAnalysis(user){
  let url = APIEndpoints["getAnalysis"];
  const request = axios.get(url);
  return {
             type:GET_ANALYSIS,
             payload: request
         }
}

Now following is the test case I have wrote:

describe('All actions', function description() {
  it('should return an action to get All Analysis', (done) => {
    const id = "costnomics";
    const expectedAction = {
      type: actions.GET_ANALYSIS
    };


    expect(actions.getAllAnalysis(id).type).to.eventually.equal(expectedAction.type).done();
  });
})

I am getting the following error:

All actions should return an action to get All Analysis:
     TypeError: 'GET_ANALYSIS' is not a thenable.
      at assertIsAboutPromise (node_modules/chai-as-promised/lib/chai-as-promised.js:29:19)
      at .<anonymous> (node_modules/chai-as-promised/lib/chai-as-promised.js:47:13)
      at addProperty (node_modules/chai/lib/chai/utils/addProperty.js:43:29)
      at Context.<anonymous> (test/actions/index.js:50:5)

Why is this error coming and how can it be solved?

I suggest you to take a look at moxios . It is axios testing library written by axios creator.

For asynchronous testing you can use mocha async callbacks .

As you are doing async actions, you need to use some async helper for Redux. redux-thunk is most common Redux middleware for it ( https://github.com/gaearon/redux-thunk ). So assuming you'll change your action to use dispatch clojure:

const getAllAnalysis => (user) => dispatch => {
  let url = APIEndpoints["getAnalysis"];
  const request = axios.get(url)
      .then(response => disptach({
         type:GET_ANALYSIS,
         payload: response.data
      }));
}

Sample test can look like this:

describe('All actions', function description() {
    beforeEach("fake server", () => moxios.install());
    afterEach("fake server", () => moxios.uninstall());

    it("should return an action to get All Analysis", (done) => {
        // GIVEN
        const disptach = sinon.spy();
        const id = "costnomics";
        const expectedAction = { type: actions.GET_ANALYSIS };
        const expectedUrl = APIEndpoints["getAnalysis"];
        moxios.stubRequest(expectedUrl, { status: 200, response: "dummyResponse" });

        // WHEN
        actions.getAllAnalysis(dispatch)(id);

        // THEN
        moxios.wait(() => {
            sinon.assert.calledWith(dispatch, {
                type:GET_ANALYSIS,
                payload: "dummyResponse"
            });
            done();
        });
    });
});

I found out it was because, I had to use a mock store for the testing along with "thunk" and "redux-promises"

Here is the code which made it solve.

const {expect}  = require('chai');
const actions = require('../../src/actions/index')

import ReduxPromise from 'redux-promise'

import thunk from 'redux-thunk'
const middlewares = [thunk,ReduxPromise] 

import configureStore from 'redux-mock-store'

const mockStore = configureStore(middlewares)


describe('store middleware',function description(){
  it('should execute fetch data', () => {
  const store = mockStore({})

  // Return the promise
  return store.dispatch(actions.getAllDashboard('costnomics'))
    .then(() => {
      const actionss = store.getActions()
      console.log('actionssssssssssssssss',JSON.stringify(actionss))
      // expect(actionss[0]).toEqual(success())
    })
})
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM