我刚开始进行redux测试,并且一直在尝试支持一个应用程序的填充测试,如果这是使用nock和redux模拟商店进行测试的完全错误的话,我非常抱歉。
//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)发布于 2017-03-08 05:26:08
您不会从axios返回链接then调用的承诺。
将雷声改为:
//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);
});
}
}您还可能需要更改测试,以便在承诺解决之前不会通过测试。如何进行此更改取决于所使用的测试库。如果你在使用摩卡,看看this answer。
附带注意:我不确定您是否有其他单元测试单独测试动作创建者到还原器,但这是一个非常完整的方法来测试这些。Redux最大的优点之一是,机器上的每一个分离的齿轮都能很容易地彼此隔离测试。
https://stackoverflow.com/questions/42663416
复制相似问题