使用react-testing-library在表单中提交时如何测试已调用的函数?

dan*_*iel 5 reactjs jestjs react-testing-library

在我的 React Signup 组件中有一个表单,用户可以在其中输入他们的电子邮件、密码和密码确认。我正在尝试使用 jest/react-testing-library 编写测试,但是由于接收到的函数调用次数为 0,预期调用次数为 1,因此测试一直失败。

我尝试过 Jest 匹配器的变体,例如 .toHaveBeenCalled()、.toHaveBeenCalledWith(arg1, arg2, ...)、toBeCalled(),所有这些都仍然期望值为 1 或更大但失败,因为接收到的数字为 0。我已经尝试了 fireEvent.click 和 fireEvent.submit ,这两个都失败了。

注册.js

export const Signup = ({ history }) => {
  const classes = useStyles();

  const [signup, setSignup] = useState({
    email: null,
    password: null,
    passwordConfirmation: null,
  });
  const [signupError, setSignupError] = useState('');

  const handleInputChange = e => {
    const { name, value } = e.target;

    setSignup({ ...signup, [name]: value });
    console.log(signup);
  };

  const submitSignup = e => {
    e.preventDefault();
    console.log(
      `Email: ${signup.email}, Pass: ${signup.password}, Conf: ${signup.passwordConfirmation}, Err: ${signupError}`
    );
};

return (
    <main>
        <form onSubmit={e => submitSignup(e)} className={classes.form}>
         <TextField onChange={handleInputChange}/>
         <TextField onChange={handleInputChange}/>
         <TextField onChange={handleInputChange}/>
         <Button
            type="submit">
           Submit
         </Button>
Run Code Online (Sandbox Code Playgroud)

注册.test.js

import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import { render, cleanup, fireEvent } from '@testing-library/react';

import { Signup } from '../Components/Signup';

afterEach(cleanup);

const exampleSignup = {
  email: 'test123@test123.com',
  password: 'test123',
  passwordConfirm: 'test123',
};

describe('<Signup />', () => {
  test('account creation form', () => {

    const onSubmit = jest.fn();

    const { getByLabelText, getByText } = render(
      <BrowserRouter>
        <Signup onSubmit={onSubmit} />
      </BrowserRouter>
    );

    const emailInput = getByLabelText(/Enter your Email */i);
    fireEvent.change(emailInput, { target: { value: exampleSignup.email } });
    const passInput = getByLabelText(/Create a Password */i);
    fireEvent.change(passInput, { target: { value: exampleSignup.password } });
    const passCInput = getByLabelText(/Confirm Password */i);
    fireEvent.change(passCInput, {
      target: { value: exampleSignup.passwordConfirm },
    });

    fireEvent.submit(getByText(/Submit/i));

    expect(onSubmit).toHaveBeenCalledTimes(1);
  });
});
Run Code Online (Sandbox Code Playgroud)

测试运行帐户创建表单的结果

expect(jest.fn()).toHaveBeenCalledTimes(expected)

Expected number of calls: 1
Received number of calls: 0
Run Code Online (Sandbox Code Playgroud)

小智 0

必须在表单标记处调用提交事件。您可以在表单标签中添加一个data-testid属性以对其进行测试。

fireEvent.submit(getByTestid('form'));