【发布时间】: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文件吗?