Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React testing library - TypeError: expect(...).toHaveTextContent is not a function

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?

like image 400
lomine Avatar asked Jan 14 '21 17:01

lomine


2 Answers

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.

like image 196
Zsolt Meszaros Avatar answered Oct 19 '22 16:10

Zsolt Meszaros


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

like image 44
Shiraz Avatar answered Oct 19 '22 15:10

Shiraz