jay*_*pee 12 forms events reactjs jestjs react-testing-library
I am trying to test that a form submits when the user presses the "Enter" key. I have a passing test for when pressing the Submit button, but I also want to be sure the form submits with the keyboard (convenience and a11y).
test("should submit when pressing enter", () => {
const handleSubmit = jest.fn();
const { getByLabelText } = render(<App handleSubmit={handleSubmit} />);
const input = getByLabelText("Name:");
fireEvent.change(input, { target: { value: "abc" } });
fireEvent.keyPress(input, { key: "Enter", code: 13, charCode: 13 });
expect(handleSubmit).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
Here is a CodeSandbox with the minimal amount of code needed.
Pet*_*nas 18
以下对我有用:
import userEvent from "@testing-library/user-event";
import { render } from "@testing-library/react";
test("should submit when pressing enter", () => {
const handleSubmit = jest.fn();
const { getByLabelText } = render(<App handleSubmit={handleSubmit} />);
const input = getByLabelText("Name:");
userEvent.type(input, "abc{enter}");
expect(handleSubmit).toHaveBeenCalled();
});
Run Code Online (Sandbox Code Playgroud)
小智 6
不太清楚交互的来源是什么,但submit可以调用input它,它似乎修复了沙箱中的测试:
fireEvent.submit(input);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8226 次 |
| 最近记录: |