【问题标题】:React-jest: some tests failed, although everything was written correctlyReact-jest:一些测试失败了,尽管一切都写得正确
【发布时间】:2020-09-15 18:44:34
【问题描述】:

我正在尝试使用 react-testing-library 测试组件,但测试仍然失败,但不知道原因。 这是我正在使用的两个文件

组件文件:

import React from "react";

const TestElements = () => {
  const [counter, setCounter] = React.useState(0);

  return (
    <>
      <h1 data-testid="counter">{counter}</h1>
    </>
  );
};

export default TestElements;

测试文件:

import React from "react";
import { render, cleanup } from "@testing-library/react";
import TestElements from "./TestElements";

afterEach(cleanup);

it("should equal to 0", () => {
  const { getByTestId } = render(<TestElements />);
  expect(getByTestId("counter")).toHaveTextContent(0);
});

【问题讨论】:

  • 它是如何失败的?请发布日志/错误的副本。
  • 我遇到类型错误:TypeError: expect(...).toHaveTextContent is not a function
  • 还有其他东西:测试套件:2 个失败,总共 2 个测试:1 个失败,总共 1 个快照:1 个文件过时,总共 0 个时间:6.456 秒,估计 8 秒运行所有相关的测试套件更改文件。

标签: jestjs


【解决方案1】:

然后可以实现你所追求的代码

it("should equal to 0", () => {
  const { getByTestId } = render(<TestElements />);
  expect(getByTestId("counter").innerHTML).toEqual("0");
});

说明:

问题是toHaveTextContent 不是一个有效的匹配器。您可以找到匹配器列表here 和更多信息expect here

React 测试库的render 返回的函数将返回一个 DOM 元素,您可以像在浏览器中那样对待它(大部分情况下)。例如,您可以对它们发出事件,例如click 来触发行为。

在您的情况下,我们可以使用innerHTML 获取元素的文本。现在expect(...)里面的部分是文本,所以我们然后使用toEqual来断言它是一个特定的文本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2023-03-12
    • 2022-11-17
    • 2015-05-09
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多