1

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

4

1 回答 1

1

文档当前声明,何时render调用“来自的查询dom-testing-library将自动返回,其第一个参数绑定到呈现的容器”

事实证明,这是文档中的一个错误,因为document.body如果将 nocontainer传递给render此处此处的代码),则查询实际上是绑定的。

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
  });
});
于 2019-01-11T02:55:08.320 回答