【问题标题】:React testing library - TypeError: expect(...).toHaveTextContent is not a functionReact 测试库 - TypeError: expect(...).toHaveTextContent is not a function
【发布时间】:2021-04-19 18:01:59
【问题描述】:

我正在按照一个简单的教程来学习反应测试库。

我有一个简单的组件,例如:

import React, {useState} from 'react';

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

  return(
    <>
      <h1 data-testid="counter" >{ counter }</h1>
      <button data-testid="button-up" onClick={() => setCounter(counter + 1)}>Up</button>
      <button data-testid="button-down" onClick={() => setCounter(counter - 1)}>Down</button>
    </>
  )
}

export default TestElements

还有一个像这样的测试文件:

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

afterEach(cleanup);

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

但如果我运行测试,我会收到以下错误:

TypeError: expect(...).toHaveTextContent is not a function

我正在使用 create-react-app 并且 package.json 显示:

"@testing-library/jest-dom": "^4.2.4",

我还需要添加笑话吗?

【问题讨论】:

  • 您是否在任何地方导入了 Jest DOM 的扩展期望?见testing-library.com/docs/ecosystem-jest-dom
  • "@testing-library/jest-dom": "^4.2.4", 在你使用 create-react-app 时包含
  • 已包含依赖项,应在src/setupTests.js 中加载(假设您使用的是默认模板)。但是你做了什么改变,这可以在全新的 CRA 应用程序中重现吗?教程是什么?
  • 这是本教程,所以我没有创建 create-react-app,而是从教程中克隆了应用程序 - freecodecamp.org/news/…
  • 作为一个简单的检查,将正确的导入添加到您的测试代码是否可以解决问题?它在我自己的教程 (blog.jonrshar.pe/2020/Nov/22/js-tdd-e2e.html) 中与 CRA4 放在一起的示例中运行良好,但 repo 缺少 setupTests 文件。

标签: javascript reactjs jestjs react-testing-library


【解决方案1】:

我认为您正在关注您在另一个问题中提到的this tutorial

要解决您的问题,您需要通过在测试文件中导入 "@testing-library/jest-dom/extend-expect" 来添加来自 jest-dom 的自定义 jest 匹配器。在 React 测试库的 full example 中也提到过。

import React from 'react';
import {render, cleanup} from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

import TestElements from './TestElements';

afterEach(cleanup);
...

编辑:我刚刚阅读了您问题下的 cmets,似乎 @jonrsharpe 已经提到您需要导入 extend-expect,但我将把这个答案留在这里。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 2019-03-22
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2022-09-29
    相关资源
    最近更新 更多