csi*_*ilk 7 unit-testing jestjs redux redux-thunk
我有一种简单的感觉,但是我有一个动作,如果满足条件,该动作将分派两个动作。
行动
export function changeDateRange({ startDate, endDate }) {
return function reload(dispatch, getState) {
if (!getState().navigation.focused) {
// If our datepicker has closed, reload the data on the page
dispatch(load());
}
dispatch({
type: types.CHANGE_DATE_RANGE,
startDate,
endDate
});
};
}
Run Code Online (Sandbox Code Playgroud)
然后我试图测试load()并用a对其进行了模拟,Jest.fn()但是当我mock.calls.length在分派后登录时是否changeDateRange()等于0?
设定
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
global.mockStore = configureMockStore([thunk]);
Run Code Online (Sandbox Code Playgroud)
测试:
import * as types from '../actionTypes';
import * as changeDateRange from './changeDateRange';
import { load } from '../reporting';
jest.mock('../reporting', () => ({
load: () => jest.fn()
}));
describe('Reducer: changeDateRange Reducer', () => {
it('should change date range', () => {
const store = mockStore({
startDate: '',
endDate: '',
navigation: {
focused: false
}
});
const dateRange = {
startDate: 'yes',
endDate: 'yes'
};
store.dispatch(changeDateRange(dateRange));
expect(store.getActions()).toEqual([
Object.assign(
{
type: types.CHANGE_DATE_RANGE
},
dateRange
)
]);
console.log(load().mock.calls.length); // === 0 ??
});
});
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
奇怪的是,这么老的问题没有答案。因为它有 8 个赞成票,所以我会为下一个找到它的人回答它。OP 错误地模拟了负载。它应该看起来像这样:
jest.mock('../reporting', () => ({
load: jest.fn() //not () => jest.fn()
}));
Run Code Online (Sandbox Code Playgroud)
然后在代码中他们可以这样做:
console.log(load.mock.calls.length); // not load().mock.calls.length
Run Code Online (Sandbox Code Playgroud)
每次调用 load 时,它都会返回一个新的模拟函数。事实上,load它本身需要成为模拟函数。
| 归档时间: |
|
| 查看次数: |
724 次 |
| 最近记录: |