反应测试库输入更改测试总是通过
react-testing-library input change test always passing
我注意到,如果我通过将值硬编码到输入字段来破坏我的表单,并且没有任何 onChange - 我的测试仍然通过!
我也尝试使用 userEvent,但测试仍然正常。
我在这里做错了什么?在浏览器中,我显然根本无法更改该值,它被固定为硬编码值。
我创建了一个沙箱来显示这个问题:https://codesandbox.io/s/dank-wave-hlsfp
反应组件:
import React from "react";
const RegisterFormExample = () => (
<form>
<label htmlFor="name">Full name</label>
<input type="name" id="name" value="this does not break a test" />
</form>
);
export default RegisterFormExample;
笑话测试:
import React from "react";
import { render, fireEvent } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import RegisterForm from "components/RegisterFormExample";
describe("RegisterForm", () => {
test("full name input", async () => {
const { getByLabelText } = render(<RegisterForm />);
const input = getByLabelText(/full name/i);
//This passes
fireEvent.change(input, {
target: {
value: "Test Example",
},
});
expect(input).toHaveValue("Test Example");
//This is passing too
await userEvent.type(input, "Test Example");
expect(input).toHaveValue("Test Example");
});
});
我的 Github 问题 here 从 eps1lon 得到了答案。
事实证明,在输入字段上设置错误的类型会搞乱测试并使其通过,永远不会猜到。
通过将类型设置为 text
而不是 name
,测试按预期失败。
<input type="text" id="name" value="test" />
我注意到,如果我通过将值硬编码到输入字段来破坏我的表单,并且没有任何 onChange - 我的测试仍然通过!
我也尝试使用 userEvent,但测试仍然正常。 我在这里做错了什么?在浏览器中,我显然根本无法更改该值,它被固定为硬编码值。
我创建了一个沙箱来显示这个问题:https://codesandbox.io/s/dank-wave-hlsfp
反应组件:
import React from "react";
const RegisterFormExample = () => (
<form>
<label htmlFor="name">Full name</label>
<input type="name" id="name" value="this does not break a test" />
</form>
);
export default RegisterFormExample;
笑话测试:
import React from "react";
import { render, fireEvent } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import RegisterForm from "components/RegisterFormExample";
describe("RegisterForm", () => {
test("full name input", async () => {
const { getByLabelText } = render(<RegisterForm />);
const input = getByLabelText(/full name/i);
//This passes
fireEvent.change(input, {
target: {
value: "Test Example",
},
});
expect(input).toHaveValue("Test Example");
//This is passing too
await userEvent.type(input, "Test Example");
expect(input).toHaveValue("Test Example");
});
});
我的 Github 问题 here 从 eps1lon 得到了答案。 事实证明,在输入字段上设置错误的类型会搞乱测试并使其通过,永远不会猜到。
通过将类型设置为 text
而不是 name
,测试按预期失败。
<input type="text" id="name" value="test" />