【发布时间】:2021-01-31 14:51:03
【问题描述】:
我正在编写一个测试以确保我的表单使用反应测试库提交,并且我也在使用反应钩子表单。我的提交方法未能在我的测试中被调用。运行此测试时出现以下错误:
● reset password should send
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
谁能解释我做错了什么?
我的组件
const ResetPassword = () => {
const { handleSubmit } = useForm();
const onSubmit = (resetFormData: { email: string }) => {
const { email } = resetFormData;
// sends email using external API
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
name="email"
type="text"
placeholder="Email Address"
/>
<button type="submit">
Send Email
</button>
</form>
);
};
export default ResetPassword;
我的测试文件
import userEvent from '@testing-library/user-event';
import { render, cleanup, screen, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
afterEach(cleanup);
it('reset password should send', async () => {
render(<ResetPassword />);
const handleSubmit = jest.fn();
const onSubmit = jest.fn();
const value = 'user@email.com';
const input = screen.getByPlaceholderText(/Email Address/i);
await userEvent.type(input, value);
await act(async () => {
userEvent.click(screen.getByRole('button', { name: /Send Email/i }));
});
expect(onSubmit).toHaveBeenCalled();
});
【问题讨论】:
-
在您的测试中使用相同的名称定义一个本地范围的函数
onSubmit不会做任何事情。对于解释器来说,这是一个完全不同的功能。您需要模拟在您的组件中调用的实际函数。这也是测试实现细节,通常是not recommended。更好的测试方法是模拟提交时发生的实际提取。
标签: javascript reactjs react-testing-library react-hook-form