当使用react-test-library在表单中提交时,可以通过以下步骤来测试已调用的函数:
import { render, fireEvent } from '@testing-library/react';
import YourComponent from './YourComponent';
const mockFunction = jest.fn();
const { getByTestId } = render(<YourComponent onSubmit={mockFunction} />);
const submitButton = getByTestId('submit-button');
fireEvent.click(submitButton);
expect(mockFunction).toHaveBeenCalled();
完整的测试代码示例:
import { render, fireEvent } from '@testing-library/react';
import YourComponent from './YourComponent';
test('should call the onSubmit function when the form is submitted', () => {
const mockFunction = jest.fn();
const { getByTestId } = render(<YourComponent onSubmit={mockFunction} />);
const submitButton = getByTestId('submit-button');
fireEvent.click(submitButton);
expect(mockFunction).toHaveBeenCalled();
});
这样,当使用react-test-library在表单中提交时,你就可以测试已调用的函数了。请注意,上述示例中的YourComponent
是一个自定义组件,你需要根据实际情况进行替换。
领取专属 10元无门槛券
手把手带您无忧上云