reactjstestingjestjsmocha.js

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.


Solution

  • 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