Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-testing-library why is toBeInTheDocument() not a function

Here is my code for a tooltip that toggles the CSS property display: block on MouseOver and on Mouse Out display: none.

 it('should show and hide the message using onMouseOver and onMouseOut events respectively', () => {     const { queryByTestId, queryByText } = render(       <Tooltip id="test" message="test" />,     )     fireEvent.mouseOver(queryByTestId('tooltip'))     expect(queryByText('test')).toBeInTheDocument()     fireEvent.mouseOut(queryByTestId('tooltip'))     expect(queryByText('test')).not.toBeInTheDocument()     cleanup()   }) 

I keep getting the error TypeError: expect(...).toBeInTheDocument is not a function

Has anyone got any ideas why this is happening? My other tests to render and snapshot the component all work as expected. As do the queryByText and queryByTestId.

like image 531
dorriz Avatar asked Jun 11 '19 15:06

dorriz


People also ask

What is toBeInTheDocument?

toBeInTheDocument simply finds element is in DOM Tree regardless of visibility. toBeVisible checks for multiple attributes to see if it's visible such as. display not equal to none.

Which function is used to firing event in react testing library?

createEvent[eventName] ​


2 Answers

toBeInTheDocument is not part of RTL. You need to install jest-dom to enable it.

And then import it in your test files by: import '@testing-library/jest-dom'

like image 57
Giorgio Polvara - Gpx Avatar answered Sep 19 '22 16:09

Giorgio Polvara - Gpx


As mentioned by Giorgio, you need to install jest-dom. Here is what worked for me:

(I was using typescript)

npm i --save-dev @testing-library/jest-dom 

Then add an import to your setupTests.ts

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

Then in your jest.config.js you can load it via:

"setupFilesAfterEnv": [     "<rootDir>/src/setuptests.ts"   ]   
like image 32
Jafin Avatar answered Sep 20 '22 16:09

Jafin