reactjs - Expect 不是反应测试库中的函数
问题描述
我正在从 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')
})
})
解决方案
您需要extend-expect
从@testing-library/jest-dom
测试文件中导入,如下所示:
import "@testing-library/jest-dom/extend-expect";
或者,如果您不想在每个测试文件中导入上述行,则需要向jest config
项目中添加一个,如下所示:
在您的项目中创建一个jest.config.js
文件,root
然后将以下代码放入其中:
//<====This is jest.config.js====>
module.exports = {
setupFilesAfterEnv: ["<rootDir>/setupTests.js"]
}
然后在项目中创建一个setupTests.js
并将root
此代码放入其中:
//<===== this is setupTests.js =====>
import "@testing-library/jest-dom/extend-expect";
推荐阅读
- android - 隐藏状态栏时变黑
- r - ggplot中带有2个不相关变量的双轴条形图?
- java - 通过扫描仪和元素使用 java 进行网页抓取
- android - startDiscovery() 冻结我的应用程序(蓝牙应用程序)
- javascript - javascript 没有读取我的 if 语句
- python - 如何在熊猫列中取消列出具有一个值的列表?
- amazon-web-services - Kubernetes mount.nfs:在 EKS 上挂载时服务器拒绝访问
- javascript - 过滤数组 React Native 时出现错误错误
- ios - 添加失败。反应本机矢量图标
- google-sheets - 用谷歌表格中的两个日期标准范围计算真假总数