【发布时间】:2021-09-01 20:50:23
【问题描述】:
我无法使用 React-bootstrap 测试表单的正确验证。 我想看看当输入模式无效时,表单验证后显示无效的反馈文本。
带有测试的工作代码框:https://codesandbox.io/s/flamboyant-cerf-7t7jq
import React, { useState } from "react";
import { Form, Button, InputGroup } from "react-bootstrap";
export default function App(): JSX.Element {
const [validated, setValidated] = useState<boolean>(false);
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setValidated(true);
};
return (
<Form
className="col-12 col-lg-5 trans-form"
noValidate
validated={validated}
onSubmit={handleSubmit}
>
<InputGroup className="my-2">
<InputGroup.Prepend>
<InputGroup.Text>Receiver Public Key</InputGroup.Text>
</InputGroup.Prepend>
<Form.Control
role="textbox"
className="text-truncate rounded-right"
type="text"
pattern="[A-Za-z0-9]{5}"
required
/>
<Form.Control.Feedback
className="font-weight-bold"
type="invalid"
role="alert"
>
Length or format are incorrect!
</Form.Control.Feedback>
</InputGroup>
<Button
role="button"
className="mt-2 font-weight-bold"
variant={"primary"}
type="submit"
block
>
Sign
</Button>
</Form>
);
}
测试
import React from "react";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";
import App from "../src/App";
describe("form validation", () => {
test("invalid receiver public key length", async () => {
render(<App />);
userEvent.click(screen.getByRole("button"));
userEvent.type(screen.getByRole("textbox"), "invalid");
expect(screen.getByRole("textbox")).toHaveValue("invalid");
expect(
await screen.findByText("Length or format are incorrect!")
).toBeVisible();
});
// this test fails, making it seem like the invalid-feedback is always present
test("valid receiver public key length", async () => {
render(<App />);
userEvent.click(screen.getByRole("button"));
userEvent.type(screen.getByRole("textbox"), "valid");
expect(screen.getByRole("textbox")).toHaveValue("valid");
await waitFor(() => {
expect(
screen.queryByText("Length or format are incorrect!")
).not.toBeVisible(); // ← FAILS
});
});
});
结果
第二次测试失败
存储库
【问题讨论】:
-
您是否考虑过使用testing-library.com/docs/ecosystem-user-event模拟实际的有效/无效输入,而不是直接触发事件?
-
是的,我有,你可以在代码沙箱中看到。不幸的是,结果相同。我什至确保在断言反馈可见性之前输入实际上改变了值
-
这可能是正确的,但我似乎无法理解可以做什么。我觉得这与我的
jest.config.js的moduleNameMapper中的.css和.scss文件的存根有关 ????我将我的存储库添加到描述中,以防它提供进一步的见解。
标签: forms validation jestjs react-bootstrap react-testing-library