使用nock和redux-mock-store错误进行Redux操作测试

时间:2017-03-08 05:07:37

标签: unit-testing testing redux redux-thunk redux-mock-store

我是redux测试的新手,并且一直在努力为一个应用程序重新填充测试,如果这是用nock和redux-mock-store进行测试的完全错误的方法,我很抱歉。

//Action in authAction.js
export function fetchMessage() {
  return function(dispatch) {
    axios.get(ROOT_URL, {
      headers: { authorization: localStorage.getItem('token') }
    })
      .then(response => {
        console.log("hi")
        dispatch({
          type: FETCH_MESSAGE,
          payload: response.data.message
        });
      })
      .catch(response => {
        console.log(response)
        //callingRefresh(response,"/feature",dispatch);
      });
  }
}

这是方法,它似乎被调用但通常会导致错误导致标题不匹配的原因。

//authActions_test.js
import nock from 'nock'
import React from 'react'
import {expect} from 'chai'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'

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

import * as actions from '../../src/actions/authActions';
const ROOT_URL = 'http://localhost:3090';

describe('actions', () => {

    beforeEach(() => {
        nock.disableNetConnect();
        localStorage.setItem("token", '12345');
    });

    afterEach(() => {
        nock.cleanAll();
        nock.enableNetConnect();
    });


  describe('feature', () => {

    it('has the correct type', () => {
      var scope = nock(ROOT_URL).get('/',{reqheaders: {'authorization': '12345'}}).reply(200,{ message: 'Super secret code is ABC123' });
      const store = mockStore({ message: '' });

      store.dispatch(actions.fetchMessage()).then(() => {
      const actions = store.getStore()
      expect(actions.message).toEqual('Super secret code is ABC123');
    })


    });
  });
});

即使删除标题并且nock拦截了呼叫。我每次都会收到此错误

TypeError: Cannot read property 'then' of undefined
  at Context.<anonymous> (test/actions/authActions_test.js:43:24)

1 个答案:

答案 0 :(得分:1)

您没有从axios返回承诺,将//Action in authAction.js export function fetchMessage() { return function(dispatch) { return axios.get(ROOT_URL, { headers: { authorization: localStorage.getItem('token') } }) .then(response => { console.log("hi") dispatch({ type: FETCH_MESSAGE, payload: response.data.message }); }) .catch(response => { console.log(response) //callingRefresh(response,"/feature",dispatch); }); } } 来电链接到。

将thunk更改为:

app.locals.siteTitle = 'Node Express';

您可能还需要更改测试,以便在promise解决之前不会通过。如何根据您使用的测试库进行更改。如果您使用的是mocha,请查看this answer

附注:我不确定您是否有其他单元测试单独测试动作创建器到减速器,但这是一种非常集成的测试方法。 Redux的一大优势是可以轻松地将每台单独的机器齿轮相互隔离测试。