Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'toBeInTheDocument' does not exist on type 'Matchers<any>'

I'm trying to write tests for my simple React App that creates a UI for a dog Shelter using API etc. I have imported the modules shown below and ran the following command

npm install jest-dom react-testing-library --save-dev 

However, I'm getting the toBeInTheDocument(); method underlined in red and the error message

"Property 'toBeInTheDocument' does not exist on type 'Matchers<any>'." 
import "react-testing-library/cleanup-after-each"; import "jest-dom/extend-expect";  import * as React from "react"; import PetCard from "./PetCard"; import Pet from "./Pet"; import { render } from "react-testing-library";  const petMock = {   id: "225c5957d7f450baec75a67ede427e9",   name: "Fido",   status: "available",   kind: "dog",   breed: "Labrador", } as Pet;  describe("PetCard", () => {   it("should render the name", () => {     const { getByText } = render(<PetCard pet={petMock} />);     expect(getByText("Fido")).toBeInTheDocument();   });  }); 

Any advice on how I can resolve this is appreciated.

like image 994
mangokitty Avatar asked Sep 09 '19 21:09

mangokitty


2 Answers

Most of the solutions above seems to tackle Babel or ESLint. If you have this problem with tslint and pure Typescript it's enough to add: @testing-library/jest-dom to your types

So that in your tsconfig.json:

"types": ["node", "jest", "@testing-library/jest-dom"], 

Please also bare in mind that you should include that library into Jest. Rather than import it in every file it is better to do it inside the config file:

setupFilesAfterEnv: [    "<rootDir>/support/setupTests.js" ], 

and then in the file setupTests.js:

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

or use to require() if using JavaScript or different configuration.

like image 131
Greg Wozniak Avatar answered Sep 20 '22 23:09

Greg Wozniak


Please make sure that the correct types are installed in your project. i.e.

npm i -D @testing-library/jest-dom@^4.2.4

From my experience the Typescript types seem to be missing from version 5.x

like image 40
Peter Avatar answered Sep 17 '22 23:09

Peter