我刚刚开始使用 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 或我的代码中的问题,但对于如何正确构建这些测试的任何建议将不胜感激。