我正在尝试在redux上测试我的异步操作,但我没有得到它。
我正在使用nock和axios,所以我试图从axios接收响应数据来测试我的行为:
describe('Async Actions', () => {
afterEach(() => {
nock.cleanAll();
});
it('should load transmissors', (done) => {
const localStorage = {
token: 'a9sd8f9asdfiasdf'
};
nock('https://tenant.contactto.care')
.get('/api/clients/1/transmissors/', {
reqheaders: { 'Authorization': "Token " + localStorage.token }
})
.reply(200, { data: [
{
"id": 12,
"zone": "013",
"client": 1,
"description": "pingente",
"identifier": "",
"general_info": ""
},
{
"id": 15,
"zone": "034",
"client": 1,
"description": "colar",
"identifier": "",
"general_info": ""
}
]});
axios.get(`/api/clients/1/transmissors/`, {
headers: { 'Authorization': "Token " + localStorage.token },
}).then(transmissors => {
console.log(transmissors);
}).catch(error => {
throw(error);
})
done();
});
});
这是我的行动:
export function loadTransmissors(clientId){
return function(dispatch){
axios.get(`/api/clients/${clientId}/transmissors/`, {
headers: { 'Authorization': "Token " + localStorage.token },
}).then(transmissors => {
dispatch(loadTransmissorsSuccess(transmissors.data, clientId));
}).catch(error => {
throw(error);
})
}
}
但是我在console.log上收到了这个错误:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): SyntaxError
我从Dan Abramov那里找到了这个答案: How to unit test async Redux actions to mock ajax response
https://github.com/reactjs/redux/issues/1716
有没有人知道如何使用redux-thunk.withExtraArgument进行测试?
提前致谢。
答案 0 :(得分:0)
我解决了我在redux thunk中通过参数注入axios的问题 https://github.com/gaearon/redux-thunk#injecting-a-custom-argument
所以我在我的商店改变了我的redux thunk:
applyMiddleware(thunk)
的
applyMiddleware(thunk.withExtraArgument({ axios }))
所以我在动作中更新了异步返回函数 从:
return (dispatch) => {
...
}
要:
return (dispatch, getState, { axios }) => {
...
}
在我的行动中。我用承诺嘲笑了一个api:
const axios = {
get: (url,params) => Promise.resolve({data: transmissors})
}
注入redux thunk:
const middleware = [thunk.withExtraArgument({axios})];
const mockStore = configureMockStore(middleware);
function asyncActions () {
return dispatch => {
return Promise.resolve()
.then(() => dispatch(transmissorsActions.loadTransmissors(1)))
}
}
我使用函数asyncActions测试我在商店的操作:
it('should load transmissors', (done) => {
const expectedAction = { type: types.LOAD_TRANSMISSORS_SUCCESS, transmissors, clientId};
const store = mockStore({transmissors: [], expectedAction});
store.dispatch(asyncActions()).then(() => {
const action = store.getActions();
expect(action[0].type).equal(types.LOAD_TRANSMISSORS_SUCCESS);
expect(action[0].transmissors).eql(transmissors);
expect(action[0].clientId).equal(1);
});
done();
});
您可以通过此示例获得有关redux-mock-store的更多信息: https://github.com/arnaudbenard/redux-mock-store/blob/master/test/index.js