我甚至不愿意为react jsonschema form编写最简单的测试。因为对输入元素的改变似乎没有反映在dom中。
给出一个类似下面这样的最小形式:
const schema = {
title: "Todo", type: "object",
properties: {
title: { type: "string", title: "Title", default: "A new task" }
}
};
const formData = { title: "First task aaa" };
export class MyForm extends React.Component {
render() { return <Form schema={schema} formData={formData} />; }
}最小测试将如下所示
test("changes input", async () => {
render(<MyForm />);
const input = screen.getByRole("textbox");
expect(input.value).toBe("First task aaa");
await userEvent.type(input, "567890", { delay: 10 });
expect(input.value).toBe("567890");
});(完整示例请访问Codesandbox。)
在表单域中键入后,文本First task aaa应替换为567890。不幸的是,它不是。input.value保持值First task aaa。
我尝试了许多触发事件和等待结果的变体,但始终保持input元素的值不变。
我在测试<MyForm />组件时遗漏了什么?在我看来是相当标准的。
发布于 2021-02-19 20:49:01
我也可以重现你的问题,看起来react-jsonschema-form在fireEvent或userEvent上不能很好地运行。
但是,使用react-doms Simulate函数,它确实可以工作:
import React from "react";
import { Simulate } from 'react-dom/test-utils'
import { render } from "@testing-library/react";
import { MyForm } from "./form.js";
// Tests in codesandbox fail in Safari - use Firefox or Chrome
// click on the "Tests" tab in the upper right.
test("changes input", async () => {
const { getByLabelText } = render(<MyForm />);
const input = getByLabelText("Title");
expect(input.value).toBe("First task aaa");
Simulate.change(input, { target: { value: '567890' }})
expect(input.value).toBe("567890");
});发布于 2021-02-25 21:49:12
因为您正在为UI使用fluent-ui表单库,这将把输入值与您的formData.title字段绑定在一起。这可能会中断userEvent.type操作。要简单地测试userEvent.type功能,可以使用纯输入元素制作表单组件,并将默认值绑定为输入元素的defaultValue。
例如:
export class MyForm extends React.Component {
render() {
return <input type="text" defaultValue="First task aaa" />;
}
}以防您在测试输出中看到以下错误:
expect(element).toHaveValue(567890)
Expected the element to have value:
567890
Received:
First task aaa567890
13 | expect(input).toHaveValue("First task aaa");
14 | userEvent.type(input, '567890');
> 15 | expect(input).toHaveValue('567890');
| ^
16 | });如您所见,userEvent.type将向当前值追加额外的输入。因此,您可以只使用Simulate.change功能或在userEvent.type行之前使用userEvent.clear函数,如下所示。
test("changes input", async () => {
render(<MyForm />);
const input = screen.getByRole("textbox");
expect(input).toHaveValue("First task aaa");
userEvent.clear(input);
userEvent.type(input, "567890");
expect(input).toHaveValue("567890");
});这个答案可能会对你的问题有所帮助。
干杯!
https://stackoverflow.com/questions/65915639
复制相似问题