I'm following a simple tutorial to learn react testing library.
I have a simple component like:
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
And a test file like:
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)
});
But if I run the test, I'm getting the following error:
TypeError: expect(...).toHaveTextContent is not a function
I'm using create-react-app and the package.json
shows:
"@testing-library/jest-dom": "^4.2.4",
Do I need to add jest as well?
I think you're following this freeCodeCamp tutorial you mentioned in your other question.
To solve your issue, you need to add the custom jest matchers from jest-dom by importing "@testing-library/jest-dom/extend-expect"
in your test file. It is also mentioned in React Testing Library's 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);
...
Edit: I've just read the comments under your question and it seems @jonrsharpe has already mentioned that you need to import extend-expect
but I'll leave this answer here.
I'd recommend having a setupTests.js file that contains:
import "@testing-library/jest-dom";
as suggested here: https://create-react-app.dev/docs/running-tests#react-testing-library
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With