我正在尝试将单元测试用例添加到我的redux操作。
我在我的操作中使用了thunk、promise-middleware
我的一个动作是这样的
export function deleteCommand(id) {
return (dispatch) => {
dispatch({
type: 'DELETE_COMMAND',
payload: axios.post(`${Config.apiUrl}delete`, { _id: id })
})
}
}这个的单元测试是
import configureMockStore from "redux-mock-store"
const middlewares = [thunk, promiseMiddleware()];
const mockStore = configureMockStore(middlewares)
it('creates DELETE_COMMAND_FULFILLED after deleting entry', (done) => {
nock('http://localhost:8081/')
.post('/delete',{
_id: 1
})
.reply(200, {})
const expectedActions = [{
type: 'DELETE_COMMAND_FULFILLED',
payload: {}
}]
const store = mockStore({
command: {
commands: []
}
})
store.dispatch(actions.deleteCommand({_id: 1}).then(function () {
expect(store.getActions())
.toEqual(expectedActions)
done();
})
})我使用的是nock、配置了thunk的redux-mock-store、promise middleware
它给了then of undefined
然后我更改了动作以返回promise,然后我得到了unhandled promise reject异常,我在动作分派调用中添加了一个catch。现在我得到了Network Error,因为它没有模拟调用。我也尝试了moxios,将axios更改为isomorphic-fetch,whatwg-fetch。似乎不起作用
我哪里做错了?
发布于 2020-01-09 08:51:26
我知道这是2017年的事,但也许有人会有同样的问题。
所以问题是deleteCommand内部的箭头函数
返回未定义。这就是为什么你会
它给出的
则是未定义的
redux TLDR:如果您将redux-thunk与redux-promise-middleware一起使用,则必须返回内部分派
here is the official redux-promise-middleware docs
解决方案非常简单:
选项1.在箭头函数内添加
export function deleteCommand(id) {
return (dispatch) => {
return dispatch({
type: 'DELETE_COMMAND',
payload: axios.post(`${Config.apiUrl}delete`, { _id: id })
})
}
}选项2. 从函数中删除大括号
export function deleteCommand(id) {
return (dispatch) =>
dispatch({
type: 'DELETE_COMMAND',
payload: axios.post(`${Config.apiUrl}delete`, { _id: id })
})
}现在你可以做
store.deleteCommand(<some id>).then(...)一般情况下,箭头函数和返回
// option 1
const arrowFuncOne = () => {
return {...someProps}
}
// option 2
const arrowFuncTwo = () => ({
...someProps
})
// This means that you returning an expression
//same as
// return a result of other function
const arrowFuncCallFunOne = () => callSomeOtherFunc()
// or
const arrowCallFunkTwo = () => {return callSomeOtherFunc()}
// However
// wrong
const arrowCallFunkNoReturn = () => {callSomeOtherFunc()}
// in this case the curly braces are just the body of the function
// and inside this body there is no return at allhttps://stackoverflow.com/questions/43986386
复制相似问题