【问题标题】:Expect is not a function in react testing libraryExpect 不是反应测试库中的函数
【发布时间】:2021-01-02 16:15:32
【问题描述】:

我正在从 freecodecamp 博客学习单元测试。我按照其中提到的所有步骤在 react 应用程序中测试 DOM 元素,但测试失败并显示以下消息:

PASS  src/App.test.js
 FAIL  src/components/TestElements.test.js
  Testing of DOM Element › should equal to 0

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

       8 |     it('should equal to 0', () => {
       9 |         const { getByTestId } = render(<TestElements />);
    > 10 |         expect(getByTestId('counter')).toHaveTextContent(0)
         |                                        ^
      11 |        });
      12 |
      13 |     it('should test button disbaled status',()=>{

      at Object.<anonymous> (src/components/TestElements.test.js:10:40)

她是我的 TestElement.js

import React from 'react'

const TestElements = () => {
 const [counter, setCounter] = React.useState(0)
  
 return (
  <>
    <h1 data-testid="counter">{ counter }</h1>
    <button data-testid="button-up" onClick={() => setCounter(counter + 1)}> Up</button>
    <button disabled data-testid="button-down" onClick={() => setCounter(counter - 1)}>Down</button>
 </>
    )
  }
  
  export default TestElements

这是我的 TestElements.test.js

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

describe('Testing of DOM Element', ()=>{
    
    afterEach(cleanup)
    it('should equal to 0', () => {
        const { getByTestId } = render(<TestElements />); 
        expect(getByTestId('counter')).toHaveTextContent(0)
       });

    it('should test button disbaled status',()=>{
        const {getByTestId} = render(<TestElements/>)
        expect(getByTestId('button-down')).toBeDisabled()

    })
    it('should test button is not disabled status', ()=>{
        const {getByTestId} = render(<TestElements/>)
        expect(getByTestId('button-up')).not.toHaveAttribute('disabled')
        
    })
})

【问题讨论】:

  • 你有jest config 文件吗?

标签: reactjs jestjs


【解决方案1】:

您需要在测试文件中从@testing-library/jest-dom 导入extend-expect,如下所示:

import "@testing-library/jest-dom/extend-expect";

或者如果您不想在每个测试文件中导入以上行,您需要像这样将jest config 添加到您的项目中:

在你项目的root创建一个jest.config.js文件,然后把这段代码放进去:

//<====This is jest.config.js====>
module.exports = {
  setupFilesAfterEnv: ["<rootDir>/setupTests.js"]
}

然后在项目的root处创建一个setupTests.js,并将这段代码放入其中:

//<===== this is setupTests.js =====>
import "@testing-library/jest-dom/extend-expect";

【讨论】:

  • 谢谢@Taghi Khavari
  • 我有一个疑问。无需导入上述语句,它对 App.js 工作得很好
  • 你的App.js 测试文件是什么?
  • 你在App test file中也使用了toHaveTextContent吗?
  • 不,我没用过。这是我的 App.test.js 文件代码
猜你喜欢
  • 1970-01-01
  • 2021-02-17
  • 2021-12-08
  • 2021-10-22
  • 1970-01-01
  • 2020-05-22
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
相关资源
最近更新 更多