171

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.

3
  • 2
    It sounds like it might be eslint complaining, have you tried changing the eslint environment? Try dropping this at the top of your test file /* eslint-env jest */
    – Adam
    Commented Sep 9, 2019 at 21:09
  • thank you this worked :)
    – mangokitty
    Commented Sep 9, 2019 at 21:15
  • /* eslint-env jest */ didnt work for me. jest version 27
    – Phoebe
    Commented Jun 18 at 0:31

27 Answers 27

254

Most of the answers here seem to address primarily Babel. If you don't use Babel it's enough to add @testing-library/jest-dom to your types.

So a few quick steps:

Make sure you've got the library installed:

yarn add -D @testing-library/jest-dom

or

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

and then link it in your tsconfig.json:

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

Now we tackle Jest configuration. Rather than import it in every test file it is better to do it in the Jest config file (usually it's called jest.config.js):

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

and then in the file setupTests.js:

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

NOTE: There was a breaking change introduced in jest-dom version 6. So for this, in the file setupTests.js:

import '@testing-library/jest-dom'

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

The alternative (for TypeScript or if you don't like adding setupTests.js) is to add globals.d.ts (in my case to the project root directory) and add there the line above (import ...).

Note: Both solution work without setting esModuleInterop.

Note: If using TypeScript, add the typings with npm install @types/testing-library__jest-dom -D

20
  • 1
    Was facing a problem with toBeVisible() not being found (TS2339: Property 'toBeVisible' does not exist on type 'JestMatchersShape<Matchers<void, any>, Matchers<Promise<void>, any>>'). Importing jest-dom/extend-expect solved it.
    – x__x
    Commented May 8, 2020 at 14:17
  • 13
    Shouldn't the "types": ["node", "jest", "@testing-library/jest-dom"] be in the ts-configs? Commented Aug 11, 2020 at 9:00
  • 1
    @JamieHutber - top level as in the documentation jestjs.io/docs/configuration#setupfilesafterenv-array. Commented Feb 23, 2022 at 13:03
  • 4
    This got almost everything working for me. Had to remove and readd the jest-dom types and restart VS Code then everything worked! i.e. I did a yarn remove @testing-library/jest-dom and a yarn add @testing-library/jest-dom@XXX where XXX was the version in my package.json I just removed. Looks like that also added "@types/testing-library__jest-dom": "^5" to my devDependencies which was likely the fix
    – Keego
    Commented Jul 7, 2022 at 22:56
  • 3
    For types, you have to add the type definitions: yarn add -D @types/testing-library__jest-dom
    – Tianhui Li
    Commented Aug 5, 2022 at 14:58
84

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

9
  • 54
    You may also need to install the types: @types/testing-library__jest-dom Commented Aug 11, 2020 at 17:32
  • 3
    This issue explains why they removed type definitions from the core.
    – shotasenga
    Commented Dec 23, 2020 at 1:57
  • 1
    @DimitriKopriwa yes, if you are using Jest for your React Native application testing
    – Peter
    Commented May 10, 2021 at 12:37
  • 2
    I think "npm i -D @testing-library/jest-dom" would be better, it solved my problems :-)
    – Michiel
    Commented Jun 29, 2021 at 10:29
  • 8
    If you are still facing this issue after adding @testing-library/jest-dom. Ensure that in your test files you have imported import '@testing-library/jest-dom';. It is mentioned in this comment Commented Nov 30, 2021 at 1:55
33

For pnpm users (who might be wondering why this works out of the box with npm), it's because pnpm uses a semi-strict node_modules layout, which means only a few packages are hoisted to the top (ie. accessible via a simple import/require)

See the docs here: https://pnpm.io/blog/2020/10/17/node-modules-configuration-options-with-pnpm#the-default-setup

That's why if you are using pnpm the quick-fix that's needed currently is

pnpm add -D @types/testing-library__jest-dom

To make it a bit more robust one could edit .npmrc and hoist only the dependency which is missing. hoisting setting.

e.g.

public-hoist-pattern[]=@types*
public-hoist-pattern[]=@vitest/expect # if using vitest
public-hoist-pattern[]=@jest/expect # if using jest
public-hoist-pattern[]=@testing-library/jest-dom

# The settings in .npmrc seem to override the default settings
public-hoist-pattern[]=*eslint*
public-hoist-pattern[]=*prettier*
1
  • Even by installing @types/testing-library__jest-dom as a dev dependency or by adding the above configuration, with pnpm I still get the error, while with npm I have no issue.
    – ifthenelse
    Commented Mar 17 at 23:00
23

eslint overrides didn't help, but adding

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

in the beginning of the test file solved it.

I found this answer here and also in the jest setup file from the facebook's official react starter app. I hope it helps.

1
  • 3
    This no longer exists with the latest version of '@testing-library/jest-dom'
    – Zargold
    Commented Oct 13, 2023 at 18:21
17

In my case it was enough to:

  • add to the package.json in devDependencies and install:
"@testing-library/jest-dom": "^5.11.9",
  • add to the .spec file:
import '@testing-library/jest-dom';
2
  • How about for react native ? Commented May 8, 2021 at 10:17
  • Adding the import in the .spec file was the key ingredient Commented Sep 7, 2023 at 14:55
10

The selected answer is usually correct if you are using babel-jest for traspilation.

For those who are still struggling due to the following errors:

  • Property 'toBeInTheDocument' does not exist on type 'JestMatchers<HTMLElement>'.
  • which leads to Cannot use import statement outside a module if you try to add import in jest.afterEnv file

Solving it with babel might lead to issues like Cannot use import statement outside a module due to the fact those two work differently. So if want to solve it purely using ts-jest (that means in your jest config you have line similar to):

transform: {
  "^.+\\.(ts|tsx)$": "ts-jest"
},

and nothing from the common answers worked then follow the steps below:

  1. The obvious, install @testing-library/jest-dom using:
npm install --save-dev @testing-library/jest-dom
  1. Add types
"types": ["node", "jest", "@testing-library/jest-dom"]

to tsconfig.json similar as above.

  1. In your jest.config.js config add the below:
...
setupFilesAfterEnv: [
  "@testing-library/jest-dom/extend-expect"
]
...
  1. Now, check your roots: ["./src"], path in your jest.config.js.
  • Create a new file called globals.d.ts in that path
  • Make sure it is matching the "included" regex within your tsconfig.json
  • Paste into globals.d.ts the following line.:
import "@testing-library/jest-dom/extend-expect"

Don't attach this line to your postEnv jest setup for ts-jest traspiler.

Run your tests and enjoy the result.

Side-notes:

  • My setup includes using jest for API testing, jest with supertest for E2E, jest with react-testing-library for React testing and browser testcafe tests with react-testing-library in the stack - and it all works now - so don't give up.
  • Make sure in your jest.config.js all the extensions are covered i.e. moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"], especially if you are trying to run .tsx tests
  • If it happens that VSCode will stop highlighting in red toBeInTheDocument() during this process and your tests still throw the error you have likely missed the valid types declaration either in tsconfig.json or in jest config.
9

The recent versions of @testing-library/jest-dom (e.g. 5.11.2) work out of the box, the issue for me was caused by cypress types conflicting with @types/chai used by @testing-library:

Since Chai and jQuery are namespaces (globals), incompatible versions will cause the package manager (yarn or npm) to nest and include multiple definitions and cause conflicts.

https://docs.cypress.io/guides/tooling/typescript-support.html#Configure-tsconfig-json

Solved by not including the cypress folder in the top-level TS config but instead adding cypress/tsconfig.json:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "baseUrl": "../node_modules",
    "types": ["cypress"]
  },
  "include": [
    "**/*.ts"
  ]
}
0
8
import '@testing-library/jest-dom/extend-expect';
import '@testing-library/jest-dom';

These lines prepended to SetupTests.ts fixed it for me.

2
  • 1
    This fixed it for me. I imported @testing-library/jest-dom/extend-expect, but I was missing @testing-library/jest-dom. In my case, the file was named setup-test-env.ts, but it's whatever you specify as the setupFilesAfterEnv export in jest.config.js. Commented Nov 16, 2021 at 11:57
  • 1
    Glad it worked for you, @ChrisCrossCrash! :-)
    – exaucae
    Commented Nov 17, 2021 at 12:05
5

As noted in the comment, it's your eslint configuration that needs to be changed. You should update your eslintrc file to include a configuration override for test files:

  ...
  overrides: [
    {
      files: [
        "**/*.test.js"
      ],
      env: {
        jest: true
      }
    }
  ]

Where "**/*.test.js" is a glob that matches the format of your test files.

Changing the eslintrc file ensures you don't have to add the eslint-env comment to the top of every test file.

See this answer as a reference: https://stackoverflow.com/a/49211283/1769777
Also see the jest environment configuration: https://eslint.org/docs/user-guide/configuring#specifying-environments

5

I dont know if someone need to read this. But i was stuck into this issue cuz i was re-importing some functions from jest. To avoid it, i remove this:

- import { describe, expect, it } from '@jest/globals';
0
5

It's an old question but I faced this problem today too.
For anyone using Vite and Vitest, together with @testing-library/react and @testing-library/jest-dom, for me this works:

// setup.ts
import { expect, afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
import * as matchers from '@testing-library/jest-dom/matchers';

// == you should add the following import: ==
import '@testing-library/jest-dom/vitest'
// ==========================================

expect.extend(matchers);

afterEach(() => {
  cleanup();
});

This import has a reference for vite to use. After doing so, it finds the tobeinthedocument() in your tests

3
  • confusing that this is part of @testing-library/jest-dom, given that jest and vitest are pretty much exclusive alternatives.... yet you are completely correct, this is what I was missing. Commented Apr 23 at 21:49
  • not sure if this is due to a change in the source code, but in my case all I needed was the line import '@testing-library/jest-dom/vitest'. Looking at the source file you can see that the lines involving matchers are handled there. Commented Apr 23 at 21:51
  • unfortunately the docs site is not clear on this; however, i eventually found correct instructions in the readme Commented Apr 23 at 21:54
4

That's my solutions for this problem in my react project:

  1. install @types/testing-library__jest-dom.
npm i -D @types/testing-library__jest-dom
  1. according to @testing-library/jest-dom typescript usage, we need import '@testing-library/jest-dom' in jest-setup.ts and add setupFilesAfterEnv to jest.config.js
// In jest-setup.ts (or any other name)
import '@testing-library/jest-dom'

// In jest.config.js add setupFilesAfterEnv
setupFilesAfterEnv: ['<rootDir>/jest-setup.js']
  1. include jest-setup.ts in tsconfig.json
{
  "include": [
    "src/**/*",
    "./jest-setup.ts"
  ],
}
1
  • This worked for me only I installed "@types/jest" instead of @types/testing-library__jest-dom. I also needed to make sure my jest-setup file was .ts not .js. The instructions for Usage of testing-library jest-dom really tell you all you need to do. Commented Nov 1, 2023 at 19:25
3

In my Next.js 13 typescript project (create by create-next-app).

I follow Next Testing Document and example with-jest project to config jest test:

  • have jest, @testing-library/[email protected], @testing-library/react, jest-environment-jsdom, @types/jest installed.
  • config jest.config.js with:
const customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  testEnvironment: 'jest-environment-jsdom',
}
  • config jest.setup.js to import '@testing-library/jest-dom'

But my test file page.test.tsx has same error: "Property 'toBeInTheDocument' does not exist on type 'Matchers<any>'."

When I rename file extension test.tsx to test.jsx (page.test.jsx) it no error. So I think it's about typescript problem.


Solution

In testing-library/jest-dom github README With TypeScript section says: you need to add "./jest-setup.ts" (for me is .js) inside your tsconfig.json include config.

  // In tsconfig.json
  "include": [
    ...
    "./jest-setup.js"
  ],

Then it fixed! I can use jest-dom expect without import @testing-library/jest-dom every test file.

2

If you're using pnpm v7 or v8, Add this to your .npmrc:

public-hoist-pattern[]=*eslint*
public-hoist-pattern[]=*prettier*
public-hoist-pattern[]=@types*

Then, run pnpm install

Reference: https://github.com/pnpm/pnpm/issues/4920#issuecomment-1226724790

2

[Sept 2023 Answer] I'm late to the party, but using create-react-app with pnpm, I managed to get rid of the problem using :

  • Dev dependency "@testing-library/jest-dom": "^6.1.3"
  • Default dependecies up-to-date :
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.5.1",

No need to add stuff in .npmrc or create Jest config files. It just worked out of the box for me.

1
  • The only answer needed in 2024!
    – Gyum Fox
    Commented Jan 22 at 9:39
1

This can happen if you are using different testing libraries together (e.g. Cypress and Jest). Both have expect with different matchers, which creates a conflict.

To fix it, you can try adding the following to tsconfig.json:

{
  ...,
  "exclude": [
    "**/*.spec.ts"
  ]
}

And the following to tsconfig.spec.json:

{
  "extends": "./tsconfig.json",
  "include": [
    "**/*.spec.ts"
  ],
  ...
}
1

I had this issue when importing types from @jest/globals as explained in the docs. testing-library/jest-dom in 5.0.1 moved their typed definitions in a separate package so that it works out of the box without any config. I needed to update testing-library/jest-dom and jest, not use any extra type library, not import any types, and it works out of the box.

setupTests.ts

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

package.json

"@testing-library/jest-dom": "5.12.0"
"jest": "27.3.1"
1

I was using only Jest and Cypress with NextJs. The issue kept occurring after trying everything until I added cypress.config.ts file to the list of exclude in my tsconfig.json file. Inside my tsconfig file, I did:

{
    "exclude": [..., "./cypress.config.ts"],
    ...
}

You can check this link for more info: https://github.com/cypress-io/cypress/issues/22059

1

I had this problem when using Cypress and Testing Library, it's notable to say that I'm also using Cypress testing library, which makes necessary to create a tsconfig.json inside Cypress folder. Down bellow I'll let the libraries related to testing I'm using and the fix I've done.

// package.json
    "@testing-library/cypress": "^10.0.1",
    "@testing-library/jest-dom": "^6.1.3",
    "@testing-library/react": "^14.0.0",
    "@testing-library/user-event": "^14.4.3",
    "@types/jest": "^29.5.4",
    "cypress": "^13.3.0",
    "jest": "^29.6.4",
    "jest-environment-jsdom": "^29.6.4",
    "ts-jest": "^29.1.1",
// tsconfig.json

{
  "compilerOptions": {
    "target": "ES5",
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    ".next/types/**/*.ts",
    "./.jest/setup.ts"
  ],
  "exclude": ["node_modules", "cypress", "cypress.config.ts"]
}
// ./cypress/ts.config.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["es5", "dom"],
    "types": ["cypress", "@testing-library/cypress", "node"]
  },
  "include": ["../cypress.config.ts", "**/*.ts"]
}

Which fix it was added cypress at this line in the root tsconfig.json:

"exclude": ["node_modules", "cypress", "cypress.config.ts"]

Hope it fix the error for you too, peace!

1
  • Thanks, this was exactly my case. I tried all the solutions but those didn't include "cypress" in the exclude array. Commented May 20 at 14:37
1

Besides all the answers mentioned in the comments above in my case replacing 'import' with 'require' helped. Even though all other inner files are imported via 'import' and other settings from the comments above were implemented too, they didn't help until I've changed the import

const { expect, describe, it } = require('@jest/globals');
1

[Feburary 2024]

Install @types/jest and @testing-library/jest-dom as a dev dependencies.

In tsconfig set;

{
  "compilerOptions": {
    "types": ["jest", "jest-dom"]
    "typeRoots": ["node_modules/@types", "node_modules/@testing-library"]
  }
}

@testing-library/jest-dom contains the types we need. The 'typeroot' entry is required because by default the 'type' property only looks in the @types folder within node_modules, so we have to point it to the @testing-library package too.

Then the 'type' field narrows down which types we actually want to utilize (from @types by default, but in this case from both paths in typeroots).

0

Please make sure you add: import "@testing-library/jest-dom/extend-expect" after: import { render } from "@testing-library/react"

import React from "react"
import { render } from "@testing-library/react"
import "@testing-library/jest-dom/extend-expect"
1
  • Can you explain how/why this would fix it? If you're importing @testing-library/jest-dom already then the rest of it is already imported
    – CWSites
    Commented Apr 24, 2023 at 18:21
0

If you are getting this error while integrating Enzyme with Jest, make sure you use jest assertion methods.

In Enzyme documentation examples chai assertions are used. Instead of that we have to use jest assertions.

Ex. Use

expect(wrapper.find(Foo)).toHaveLength(3);

instead of

expect(wrapper.find(Foo)).to.have.lengthOf(3);
0

I messed with this for a couple of hours and read all the Q&A sites. Nothing worked, except for moving @testing-library/react and @testing-library/jest-dom out of devDependencies, and into dependencies.

I don't know why they're needed for production exactly, but it works.

0

I spent a day and use tons of tutorials and documentation to handle this issue but it didn't work out. And only two steps helped me.

  1. I just removed imports @jest/globals from test files.
  2. I was trying to get rid of this issue during some package installation I noticed that I got changes in "scripts" field in package.json, and I reverted it from "test": "jest" to "test": "react-scripts test" and It works now.
0

I was doing everything right as suggested by above answers but was doing a silly mistake of not not including the file with the line import '@testing-library/jest-dom'; in tsconfig.json

My tsconfig configuration was

  "include": ["src/**/*"],

So I changed it to

  "include": ["src/**/*", "./jest.setup.js"],

in tsconfig.json

0

In my case, (Vite + React Typescript + Jest), after following other answers, the problem persisted. I had to add the tsconfig.spec.json to the tsconfig.json references.

tsconfig.spec.json

{
  "extends": ["./tsconfig.app.json"],
  "compilerOptions": {
    "types": ["node", "jest", "@testing-library/jest-dom"],
  },
  "include": ["src", "./jest.setup.ts"],
  "exclude": []
}

tsconfig.app.json

{
  // ...
  "include": ["src"],
  "exclude": ["**/*.spec.ts", "**/*.spec.tsx"]
}

tsconfig.json

{
  "files": [],
  "references": [
    { "path": "./tsconfig.app.json" },
    { "path": "./tsconfig.spec.json" },
    { "path": "./tsconfig.node.json" }
  ]
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.