When performing front-end testing using Jest in combination with @testing-library
, the following type error is often encountered:
describe("Card", () => { it("should render the name", () => { const { getByText } = render(<Card pet={petMock} />); expect(getByText("name")).toBeInTheDocument(); });});
When running npm test
, the test case can pass normally, but the editor will prompt the following error, which greatly affects my mood.
Property 'toBeInTheDocument' does not exist on type 'Matchers<any>'
Analysis of the Error Cause
toBeInTheDocument
is an extended matcher provided by the @testing-library/jest-dom
library, which is not explicitly imported in the test file or automatically loaded through the Jest configuration. The TypeScript compiler cannot recognize the undeclared matcher type, resulting in a type checking failure.
Solutions
Next, solve this problem step by step.
- Install the necessary dependencies
First, make sure that @testing-library/jest-dom
is installed in the project:
# Using npmnpm install @testing-library/jest-dom -D# Or using pnpmpnpm add @testing-library/jest-dom -D
- Configure the
types
field intsconfig.json
In the project's tsconfig.json
file, add @testing-library/jest-dom
to the types
field:
{ "compilerOptions": { "types": ["@testing-library/jest-dom"] }}
Next, create a setupTests.ts
file in the root directory to import the @testing-library/jest-dom
matchers:
import "@testing-library/jest-dom";
Then, in the Jest configuration file, such as in jest.config.js
or the jest
field in package.json
, add the setupFilesAfterEnv
configuration item and specify the path of the setupTests.ts
file:
{ "jest": { "setupFilesAfterEnv": ["<rootDir>/setupTests.ts"] }}
If your version of jest-dom
is 5.x, then you need to import @testing-library/jest-dom/extend-expect
in the setupTests.ts
file:
import "@testing-library/jest-dom/extend-expect";
Through the above steps, the error prompt of Property 'toBeInTheDocument' does not exist on type 'Matchers<any>'
can be solved.