Answer a question

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?

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.

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐