我得到错误的expect(jest.fn()).toHaveBeenCalledWith(...expected)调用数: 0。
代码:
There is a component on submitting * as form value it will call formik on submit which will
call api asyncronously
and storing data in searchResult.Then i am checking if entered value is * and length of
response is greater than 1 then i am calling history.push on outside(i mean not inside any
function)and it is working fine but when i am writing test cases for this it is showing no
call generated.
const history = useHistory();
interface LocationRoute {
pathname: string,
state: any
}
if (searchResult.data&& formvalue == '*') {
if (searchResult.data.length > 1) {
console.log('length greater than 1')
history.push({
pathname: '/alldata',
state: { "name": "John", "EndDate": "16-Jun-2024", "Id": "1252", "StartDate": "17-Jun-2020"}
} as LocationRoute);
}
}
测试用例:
const mockHistoryPush = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
push: mockHistoryPush,
}),
}));
describe()......starts
it('should render card with data when clicked for *', async () => {
SearchWrapper = mount(<CustomerSearch />);
..... checked before clicking submit...
......
await act(async () => {
SearchWrapper.find('button#submit2').simulate('click');
});
await act(async () => {
SearchWrapper.update();
});
expect(mockHistoryPush).toHaveBeenCalledWith(locationStateMock2);
}
而locationstatemock2是
export const locationStateMock2 = { "pathname": "/alldata", "state": { "name": "John", "EndDate": "16-Jun-2024", "Id": "1252", "StartDate": "17-Jun-2020"}}
我所犯的错误就是。
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: {"pathname": "/alldata", "state": { "name": "John", "EndDate": "16-Jun-2024", "Id": "1252", "StartDate": "17-Jun-2020"}}
Number of calls: 0
我使用我在代码‘长度大于1’中保留的控制台语句进行搜索,在那里我看到这个错误
console.error
Error: Uncaught [TypeError: Cannot read property 'push' of undefined]
at reportException (C:\react\copy\front-end\node_modules\jsdom\lib\jsdom\living\helpers\runtime-script-errors.js:62:24)
at innerInvokeEventListeners (C:\react\copy\front-end\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:333:9)
at invokeEventListeners (C:\react\copy\front-end\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:274:3)
有人能事先帮我吗please.Thanks
发布于 2021-09-06 08:44:53
您可以尝试的一件事是删除某些异步,只在act
中包装触发setState的方法。
await act(() => {
SearchWrapper.find('button#submit2').simulate('click');
});
SearchWrapper.update(); // this one is not async so no need to wrap AFAIK
虽然我不能确定,因为没有显示单击处理程序。
https://stackoverflow.com/questions/69066095
复制相似问题