我刚刚开始使用 react-testing-library,所以我猜测这最终归结于用户错误,但我看到以下行为对我来说没有意义。
对于在新创建的 CRA 应用程序中运行以下测试,并使用 jest-dom 3.0.0 和 react-testing-library 5.4.4:
import React from "react";
import { render } from "react-testing-library";
import "jest-dom/extend-expect";
import Component from "./Component";
describe("Verify UI state based on jobs", () => {
it("mounts with no previous data", () => {
const { getByTestId } = render(<Component data={[]} />);
expect(getByTestId("refresh-button")).toBeDisabled();
});
it("mounts with previous data", () => {
const { getByTestId } = render(<Component data={["hi"]} />);
expect(getByTestId("refresh-button")).not.toBeDisabled();
});
});
/*
const Component = props => {
return (
<div>
<button data-testid="refresh-button" disabled={props.data.length === 0}>
Refresh
</button>
</div>
);
};
*/
事情是我得到以下失败:
根据作业验证 UI 状态 › 使用以前的数据挂载
expect(element).not.toBeDisabled()
Received element is disabled:
<button data-testid="refresh-button" disabled="" />
13 | it("mounts with previous data", async () => {
14 | const { getByTestId } = render(<Component data={["hi"]} />);
> 15 | expect(getByTestId("refresh-button")).not.toBeDisabled();
| ^
16 | });
17 | });
18 |
at Object.toBeDisabled (src/Component.test.js:15:47)
但是,如果我禁用第一个测试,那么第二个现在应该通过。如果我重新排序,第一个测试总是通过而第二个总是失败,即使第一个测试是“使用先前数据的安装”测试。
不确定这是否是测试库、jest-dom 或我的代码中的问题,但任何有关如何正确构建这些测试的建议将不胜感激。
文档目前声明 whenrender
被调用时“来自的查询dom-testing-library
自动返回,它们的第一个参数绑定到呈现的容器”。
事实证明,这是文档中的一个错误,因为document.body
如果将 nocontainer
传递给render
(代码here和here),查询实际上是绑定到的。
react-testing-library
使用 DOM,除非cleanup
在测试之间调用,否则来自早期测试的 DOM 元素仍将存在,并将包含在以后的查询结果中。
在这种情况下Component
,document.body
在第二次测试期间两个元素都存在,并且由于getByTestId
查询document.body
最终会找到它们,当它找到多个时,它返回它找到的第一个。
这意味着在第二个测试中会Component
返回来自第一个测试的getByTestId
,这会导致测试失败,因为第一个组件被禁用。
要解决此问题,请确保cleanup
在每次测试后调用以删除在先前测试中添加的任何 DOM 元素:
import React from "react";
import { render, cleanup } from "react-testing-library";
import "jest-dom/extend-expect";
afterEach(cleanup); // clean up the DOM after each test
describe("Verify UI state based on jobs", () => {
it("mounts with no previous data", () => {
const { getByTestId } = render(<Component data={[]} />);
expect(getByTestId("refresh-button")).toBeDisabled(); // SUCCESS
});
it("mounts with previous data", () => {
const { getByTestId } = render(<Component data={["hi"]} />);
expect(getByTestId("refresh-button")).not.toBeDisabled(); // SUCCESS
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句