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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With