gpt4 book ai didi

reactjs - Expect 不是 react 测试库中的函数

转载 作者:行者123 更新时间:2023-12-02 16:20:51 25 4
gpt4 key购买 nike

我正在从 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')

})
})

最佳答案

您需要在测试文件中从 @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";

关于reactjs - Expect 不是 react 测试库中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65541311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com