嗨,我有一个函数,如下所示:
MyComponent.js-------
const somefunction = () => {
if (someCondition) {
dispatch(someActionMethod({
id: 01,
empName: 'Adam'
}).then((result) => {
setSomeState(result.data);
})
)
}
}
尝试了很多方法来模拟调度的someActionMethod,但所有的努力都失败了。
测试文件:
import React from 'react';
import * as redux from 'react-redux';
import { render } from '@testing-library/react';
const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch');
const mockDispatchFn = jest.fn();
describe('<MyComponent />', () => {
const props = {};
mockDispatchFn.mockReturnValue(
[{data1},{data2}]
);
let componentRendering;
beforeEach(() => {
componentRendering = render(
<MyComponent props={ props } />
)});
it('test component', ()=> {
expect(componentRendering.container.innerHTML).not.toBeNull();
});
});
抛出错误:
Cannot read properties of undefined (reading 'then')
从错误消息中我的假设是你的代码在某处期待一个承诺。
堆栈跟踪将包含有关在特定行抛出此错误的组件的信息。
我建议您检查您的代码和模拟所需的所有方法
我希望这有助于解决错误
您是否尝试过模仿useDispatch
而不是模仿someActionMethod
?
import * as redux from 'react-redux';
const useDispatchSpy = jest.spyOn(redux, 'useDispatch');
const mockDispatchFn = jest.fn();
// One of these should work
mockDispatchFn.mockReturnValue([{data1}, {data2}]);
useDispatchSpy.mockReturnValue(mockDispatchFn);
与你更新响应我试试这个:
describe('<MyComponent />', () => {
it('test component', () => {
const props = {};
const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch');
const mockDispatchFn = jest.fn();
mockDispatchFn.mockReturnValue(
[{ data1 }, { data2 }],
);
render(<MyComponent {...props} />);
// your assertions here
});
});
您是否与中间件一起使用它?我不确定调度返回一个承诺或任何值没有使用中间件。
顺便说一下,mock一个react redux钩子并不是一个推荐的方法,实际上你可以看到,在react-redux包的版本8中,它甚至是不可能的。