REDUX操作测试与Nock和Redux Mock商店错误



我是REDUX测试的新手,并且一直在尝试备份填充测试,如果这是与Nock和Redux-Mock一起进行测试的完全错误的方法,我对此做出了很抱歉。商店。

//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);
      });
  }
}

这是方法,它似乎被调用了,但通常是指nock失败原因不匹配的原因。

//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)

您没有将承诺从Axios返回到then调用。

将thunk更改为:

//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);
      });
  }
}

您可能还需要更改测试,以便在承诺解决之前不会通过。如何进行此操作,具体取决于您使用的测试库。如果您使用的是摩卡咖啡,请查看此答案。

旁注:我不确定您是否有其他单元测试将动作创建者分别测试到还原器,但这是一种非常集成的测试方法。Redux的最大优势之一是,可以彼此孤立地测试机器的每个单独齿轮。

相关内容

  • 没有找到相关文章

最新更新