英文:
Dispatch is not a function when testing a redux action
问题
我正在学习使用Jest和Enzyme为操作创建函数编写测试。这是我在React Native中使用的一个操作创建函数。
请考虑下面的代码:
import {
FETCH_FAIL
} from './types';
export const fetchFail = (dispatch) => {
dispatch({
type: FETCH_FAIL,
payload: "An error occurred. Try again later."
});
};
我为这个操作创建函数编写了以下测试:
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
test('should fail fetch', async () => {
const payload = {
type: FETCH_FAIL,
payload: "An error occurred. Try again later."
}
const store = mockStore({ data:[], isConnected: false });
expect(store.dispatch(actions.fetchFail())).toEqual(payload);
})
我的测试失败,出现了以下结果:
TypeError: dispatch is not a function
我做错了什么?
英文:
I'm learning to write tests for action creators with Jest and Enzyme. This is an action creator that I am using with React Native.
Please consider the code below:
import {
FETCH_FAIL
} from './types';
export const fetchFail = (dispatch) => {
dispatch({
type: FETCH_FAIL,
payload: "An error occurred. Try again later."
});
};
I wrote the following test for this action creator:
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
test('should fail fetch', async () => {
const payload = {
type: FETCH_FAIL,
payload: "An error occurred. Try again later."
}
const store = mockStore({ data:[], isConnected: false });
expect(store.dispatch(actions.fetchFail())).toEqual(payload);
})
My test fails with the following result:
> TypeError: dispatch is not a function
What am I doing wrong?
答案1
得分: 4
首先,您需要从您的“thunk”返回分发的操作
```js
export const fetchFail = (dispatch) => {
return dispatch({
type: FETCH_FAIL,
payload: "An error occurred. Try again later."
});
};
然后不要调用“thunk”,而是传递引用(删除括号),因为“thunk”中间件在操作为函数时将“dispatch”作为第一个参数调用您的操作
test('should fail fetch', async () => {
const payload = {
type: FETCH_FAIL,
payload: "An error occurred. Try again later."
}
const store = mockStore({ data:[], isConnected: false });
// 删除fetchFail()周围的括号
expect(store.dispatch(actions.fetchFail)).toEqual(payload);
})
英文:
First you will need to return the dispatched action from your thunk
export const fetchFail = (dispatch) => {
return dispatch({
type: FETCH_FAIL,
payload: "An error occurred. Try again later."
});
};
And then don't call the thunk
but pass the reference(remove the parentheses) because the thunk
middleware is calling your action passing dispatch
as the first argument when the action is a function
test('should fail fetch', async () => {
const payload = {
type: FETCH_FAIL,
payload: "An error occurred. Try again later."
}
const store = mockStore({ data:[], isConnected: false });
// removed the parentheses around fetchFail()
expect(store.dispatch(actions.fetchFail)).toEqual(payload);
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论