Ramji
Ramji

Reputation: 75

Expect is not a function in react testing library

I'm learning unit test in react from freecodecamp blog. I followed all the steps mentioned in that for testing a DOM Element in the react app but test fails by saying the following message:

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)

Hers is my 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

And here is my 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')
        
    })
})

Upvotes: 2

Views: 8798

Answers (1)

Taghi Khavari
Taghi Khavari

Reputation: 6582

You need to import extend-expect from @testing-library/jest-dom in your test file like this:

import "@testing-library/jest-dom/extend-expect";

or if you don't want to import above line in every test file you need to add a jest config to your project like this:

Create a jest.config.js file in the root of your project and then put this code in it:

//<====This is jest.config.js====>
module.exports = {
  setupFilesAfterEnv: ["<rootDir>/setupTests.js"]
}

and then create a setupTests.js at the root of the project and put this code in it:

//<===== this is setupTests.js =====>
import "@testing-library/jest-dom/extend-expect";

Upvotes: 7

Related Questions