![](/img/trans.png)
[英]In a mocked function, how do I get the input parameters that were passed into it?
[英]Mocked function get triggered but toHaveBeenCalledWith do not recognize it
我从react-naitive/navigation
嘲笑了useNavigation()
钩子,但开玩笑不认识它。
Jest 给我一个错误,function 没有被调用,但是当我记录 function 时它被触发了。
我已经尝试过用waitFor
包装他们期望的但后来我得到一个 typescript 捕获错误Error: Uncaught [TypeError: Cannot read properties of undefined (reading 'catch')]
我的笑话测试:
jest.mock('@react-navigation/native', () => {
const actualNav = jest.requireActual('@react-navigation/native');
return {
...actualNav,
useNavigation: () => ({
// when I do () => { console.log('trigger') } it will be called
navigate: jest.fn(),
}),
useRoute: () => ({
params: { email: '' },
}),
};
});
....
it.only('should navigate to resend screen when button is pressed', async () => {
const { getByTestId } = render(
withStoreProvider(<EmailVerificationPending />),
);
await waitFor(() => {
expect(
getByTestId('emailVerificationPendingScreen_moreInfoCta'),
).toBeTruthy();
});
fireEvent.press(getByTestId('emailVerificationPendingScreen_moreInfoCta'));
expect(navigation.navigate).toHaveBeenCalledWith(
RootScreens.SignUpNavigator,
{
screen: SignUpScreens.EmailVerificationResend,
params: {
email: '',
},
},
);
});
错误信息:
● features/signup/presentation/email-verification/pending-screen › should navigate to resend screen when button is pressed
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: "RootScreens_SignUpNavigator", {"params": {"email": ""}, "screen": "SignUpScreens_EmailVerificationResend"}
Number of calls: 0
64 | fireEvent.press(getByTestId('emailVerificationPendingScreen_moreInfoCta'));
65 |
> 66 | expect(navigation.navigate).toHaveBeenCalledWith(
当您尝试使用 Jest 测试框架测试模拟的 function 时,可能会出现此错误消息,并且测试失败是因为正在调用模拟的 function 但断言 toHaveBeenCalledWith 无法识别它。
以下是一些可能的解决方案:
确保您正在导入正确的模拟 function 并且它在代码中的正确位置被调用。
检查传递给模拟 function 的 arguments 是否匹配传递给 toHaveBeenCalledWith 的 arguments
检查模拟实现是否正确,您应该使用 jest.fn() 或 jest.spyOn() 创建模拟 function
确保您对 toHaveBeenCalledWith 断言使用正确的语法。
尝试调试测试以检查模拟的 function 是否被调用。
确保您正确导入和调用导航 function,并且使用正确的 arguments 和参数调用它。
确保在按钮按下事件之后而不是之前调用导航 function。
确保在正确的屏幕中调用导航 function,并且测试不会在错误的屏幕中查找它。
尝试使用 .toHaveBeenCalled() 而不是 .toHaveBeenCalledWith()
确保测试用例没有被跳过或忽略。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.