Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Property 'toBeInTheDocument' does not exist on type 'JestMatchers<HTMLElement>' #546

Open
khairalanam opened this issue Nov 1, 2023 · 35 comments

Comments

@khairalanam
Copy link

  • @testing-library/jest-dom version: 6.1.4
  • node version: 18.17.1
  • jest version: 29.7.0
  • npm version: 10.2.0

Other dependencies:

dependencies

Relevant code or config:

import { render, screen } from "@testing-library/react";
import Home from "@/app/page";

it("should have Docs text", () => {
  render(<Home />);

  const myElement = screen.getByText("Docs");

  expect(myElement).toBeInTheDocument();
});

What you did:

I was following a Next.js Testing tutorial by Dave Gray to learn more about React Testing. I followed the tutorial until the 17-minute mark where the error occurred.

What happened:

This is the error:
Error

Reproduction:

The steps from the beginning until the 17th-minute mark of the tutorial will give the error.

Problem description:

Property 'toBeInTheDocument' does not exist on type 'JestMatchers'. It seems that it has something to do either with TypeScript, or the Nextjs 14, or with the latest release of testing-library/jest-dom

Suggested solution:

The only solution, which seems temporary, is to roll back to an older version like 5.16.5 or 5.17. This solves the problem.

@fattila16
Copy link

fattila16 commented Nov 3, 2023

For me the following seems to be solving the issue:
setupAfterEnv.ts

import '@testing-library/jest-dom/jest-globals';
import '@testing-library/jest-dom';

Update:

Eh maybe it is flaky because after a couple of TS server restarts now it does not work .... Anyway maybe this is not the correct solution then.

@khairalanam
Copy link
Author

That's pretty good. It has to be added to the config file after installing the library.

@Dyn4sty
Copy link

Dyn4sty commented Nov 7, 2023

I've come across the issue you're experiencing and I believe I have a solution that might help you.

If you add the following line to your tsconfig.json under compilerOptions:

{
  "compilerOptions": {
    // ... other options
    "types": ["@testing-library/jest-dom"],
    // ... other options
  }
}

This will inform TypeScript to include the type definitions from @testing-library/jest-dom, which should resolve the type errors you're seeing.

@khairalanam
Copy link
Author

This too seems solid but much cleaner. Nice!

@42x42x42
Copy link

in my case replacing import with require helped (all other fixes suggested above were already implemented and didn't help)
const { expect, describe, it } = require('@jest/globals');

@wslp12
Copy link

wslp12 commented Nov 23, 2023

pnpm install --save-dev "@types/jest"
i just do install types library it work for me
not any config file edit

@AshfaqKabir
Copy link

in my case replacing import with require helped (all other fixes suggested above were already implemented and didn't help) const { expect, describe, it } = require('@jest/globals');

Thanks bro it worked, none of the solutions were working

@chrisrhymes
Copy link

I have tried adding the import '@testing-library/jest-dom/jest-globals'; to the jest.setup.ts file and adding the types to the tsconfig.json file as detailed above, but I still get the type errors showing in VS Code.

Strangely, when I open the jest.setup.ts file in VS Code, the type errors suddenly disappear and everything works as expected? Am I missing a step from my configuration?

@Noyabronok
Copy link

import '@testing-library/jest-dom'; is the only thing working for me, but I have to do it in every test file 👎

@LeeBingler
Copy link

The only solution that as work with me (I'm using Nextjs 14.0.3) is to modify the tsconfig.json and add: "types": ["@testing-library/jest- to compilerOptions

@Noyabronok
Copy link

Noyabronok commented Nov 30, 2023

Woohoo, I got the compilerOptions: { "types": ["@testing-library/jest-dom"] } in tsconfig.json change working!

tsconfig file needed the following change:

from:

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

to:

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

Appears that only files at the root or src directory were having tsconfig changes applied.

This took care of VSCode error. Unfortunately I still needed import '@testing-library/jest-dom' in my jest-setup.tsx file to remove the error from test runs

@chrisrhymes
Copy link

The comment above by @Noyabronok has pointed me in the right direction. Thanks.

I had "src/**/*.test.tsx" in the "exclude" array in my tsconfig.json for some reason 🤦 .

Removing this seems to have resolved the issue in VS Code for me now.

leerob pushed a commit to vercel/next.js that referenced this issue Dec 13, 2023
This PR updates the testing guides to use App Router and TypeScript,
also updates `/examples` to show `app` and `pages` examples.

## Overview

- [x] Create a new "Testing" section that is shared between `app` and
`pages`.
- [x] Explain the differences between E2E, unit testing, component
testing, etc.
- [x] Recommend E2E for `async` components as currently none of the
tools support it.
- [x] Update setup guides for **Cypress**, **Playwright**, and **Jest**
with latest config options, and examples for `app` and `pages`.
- [x] Add new guide for **Vitest**
- [x] Clean up `/examples`: use TS, show `app` and `pages` examples,
match docs config

## Cypress

- [x] E2E Tests
- [x] Component Testing
  - [x] Client Components
  - [x] Server Components
  - [ ] `async` components

**Blockers:** 
- TS: `Option 'bundler' can only be used when 'module' is set to
'es2015' or later`. In **tsconfig.json** compilerOptions, Next.js uses
"moduleResolution": "bundler", changing it to "node" fixes the issue but
it can have repercussions.
  - cypress-io/cypress#27731 
- Version 14 is currently not supported for component testing
  - cypress-io/cypress#28185

## Playwright

- [x] E2E Tests

## Jest

- [x] Unit Testing
   - [x] Client Components
   - [x] Server Components
- [ ] `async` components:
testing-library/react-testing-library#1209
   - [x]  'server-only': #54891
- [x] Snapshot Testing

**Blockers:**
- TS: testing-library/jest-dom#546
- None of the solutions in the issue work with Next.js v14.0.4 and TS v5

## Vitest 

- [x] Unit Testing
  - [x] Client Components
  - [x] Server Components
  - [ ] `async` components
  - [x] 'server-only'
 - [x] Update vitest example
- [x] Handles CSS, and CSS modules imports
- [x] Handles next/image

## Other

- #47448
- #47299
agustints pushed a commit to agustints/next.js that referenced this issue Jan 6, 2024
This PR updates the testing guides to use App Router and TypeScript,
also updates `/examples` to show `app` and `pages` examples.

## Overview

- [x] Create a new "Testing" section that is shared between `app` and
`pages`.
- [x] Explain the differences between E2E, unit testing, component
testing, etc.
- [x] Recommend E2E for `async` components as currently none of the
tools support it.
- [x] Update setup guides for **Cypress**, **Playwright**, and **Jest**
with latest config options, and examples for `app` and `pages`.
- [x] Add new guide for **Vitest**
- [x] Clean up `/examples`: use TS, show `app` and `pages` examples,
match docs config

## Cypress

- [x] E2E Tests
- [x] Component Testing
  - [x] Client Components
  - [x] Server Components
  - [ ] `async` components

**Blockers:** 
- TS: `Option 'bundler' can only be used when 'module' is set to
'es2015' or later`. In **tsconfig.json** compilerOptions, Next.js uses
"moduleResolution": "bundler", changing it to "node" fixes the issue but
it can have repercussions.
  - cypress-io/cypress#27731 
- Version 14 is currently not supported for component testing
  - cypress-io/cypress#28185

## Playwright

- [x] E2E Tests

## Jest

- [x] Unit Testing
   - [x] Client Components
   - [x] Server Components
- [ ] `async` components:
testing-library/react-testing-library#1209
   - [x]  'server-only': vercel#54891
- [x] Snapshot Testing

**Blockers:**
- TS: testing-library/jest-dom#546
- None of the solutions in the issue work with Next.js v14.0.4 and TS v5

## Vitest 

- [x] Unit Testing
  - [x] Client Components
  - [x] Server Components
  - [ ] `async` components
  - [x] 'server-only'
 - [x] Update vitest example
- [x] Handles CSS, and CSS modules imports
- [x] Handles next/image

## Other

- vercel#47448
- vercel#47299
@dtrenz
Copy link

dtrenz commented Jan 12, 2024

Adding compilerOptions: { "types": ["@testing-library/jest-dom"] } in tsconfig.json didn't work for me because it overrides my existing "typeRoots".

The only solution I've found is adding import "@testing-library/jest-dom"; to every test file, which is a bummer.


Update: I was able to resolve this!

If, like me, you are configuring typeRoots in tsconfig.json and the above solution using the types property doesn't work for you, you can instead update typeRoots:

"typeRoots": ["node_modules/@types", "node_modules/@testing-library"]

@piecyk
Copy link

piecyk commented Jan 15, 2024

Better is just point ts compiler to setupTests.ts file with import to @testing-library/jest-dom by adding it to tsconfig.json include option.

checkout this comment nrwl/nx#9140 (comment) btw there is no need to install @types/testing-library__jest-dom in first step

@Danielvandervelden
Copy link

So I have this import inside of my setupTests.ts:

import "@testing-library/jest-dom";

And when I have the setupTests.ts files actually open in my IDE, it's all good. No complaints. Now when I close the setupTests.ts file, my IDE starts complaining that inTheDocument() doesn't exist on JestMatchers... And then when I open setupTests.ts again, it's all good and dandy. Anybody else had this problem?

@cheater
Copy link

cheater commented Feb 12, 2024

since this is one of the main google hits, I thought I'd share what the solution is. There are two problems: 1. jest-dom 5.x doesn't have TS types and 2. expect needs to be extended.

First, we'll uninstall jest-dom and install a 4.x version:

yarn remove @testing-library/jest-dom
yarn add -D @testing-library/jest-dom@^4.2.4

You can use the analogous npm commands instead of yarn.

Then, add this to src/setupTests.ts:

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

Doing these two things alone worked for me.

BTW, I stumbled upon this while following a tutorial that was based off of create-react-app, using the command yarn create react-app myname --template typescript.

@sugubei
Copy link

sugubei commented Mar 6, 2024

// @ts-ignore 就好了

@akiik
Copy link

akiik commented Mar 8, 2024

I just downgraded from jest-dom 6.x to 5.x and everything is green again.

@gabrielrochas
Copy link

That works for me

  1. Create/update jest.setup.ts:

    import '@testing-library/jest-dom';
  2. Update jest.config.ts:

    // ...other configs
    setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  3. Add type definitions in tsconfig.json:

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

@emmarq
Copy link

emmarq commented Mar 19, 2024

As this is still alive at this date i have to say what just worked for me right now.
I updated @testing-library/jest-dom to the latest and in the jest setup file instead of importing it as import '@testing-library/jest-dom/extend-expect';, I imported it now as this import '@testing-library/jest-dom/jest-globals';

The way i use the jest functions in typescript is doing explicit imports like import { describe, expect, test } from '@jest/globals'; from the also required package @jest/globals

https://jestjs.io/docs/getting-started#type-definitions
https://github.com/testing-library/jest-dom/releases/tag/v6.0.0

i couldn't get it working with @types/jest but i dont care about it, i rather use @jest/globals.

@peguerosdc
Copy link

instead of importing it as import '@testing-library/jest-dom/extend-expect';, I imported it now as this import '@testing-library/jest-dom/jest-globals';

After hours of debugging, this is what finally made the trick for me. Thanks!

@alirezarastineh
Copy link

@khairalanam I was taking the same course with Dave Gray and encountered the same issue. Initially, I had errors with it and expect which were also shown in the video. I resolved these errors by running npm i -D @types/jest After addressing this, I faced the exact same error as you did, and resolved it by removing extend-expect from the import statement @testing-library/jest-dom/extend-expect in jest.setup.ts file.

The reason is that @testing-library/jest-dom no longer requires a separate import of @testing-library/jest-dom/extend-expect as it might have in earlier versions. Therefore, if you are using version 6.0 or higher, you should import @testing-library/jest-dom directly, without including the extend-expect path.

@pathliving
Copy link

I tried every solution from this thread, but only one solved the problem

renaming jest.setup.ts to jest.setup.js

p.s. ts-node not impact

@comadaihiep92
Copy link

I've come across the issue you're experiencing and I believe I have a solution that might help you.

If you add the following line to your tsconfig.json under compilerOptions:

{
  "compilerOptions": {
    // ... other options
    "types": ["@testing-library/jest-dom"],
    // ... other options
  }
}

This will inform TypeScript to include the type definitions from @testing-library/jest-dom, which should resolve the type errors you're seeing.

this working for me :D

@TeemuKoivisto
Copy link

I just realized looking at my expect type signature that my global Cypress types overrode my Jest types. Removing "cypress" from the "types" fixed it.

@rxy001
Copy link

rxy001 commented May 31, 2024

This seems to have resolved the issue:

  1. Adding import '@testing-library/jest-dom/jest-globals' to jest.setup.ts.
  2. Adding setupFilesAfterEnv: ['<rootDir>/tests/jest.setup.ts'], to jest.config.ts.
  3. Adding "types": ["@testing-library/jest-dom/jest-globals"] to tsconfig.ts.

or adding import "@testing-library/jest-dom" to every test file.

@zhaoyangwuuuu
Copy link

This seems to have resolved the issue:

  1. Adding import '@testing-library/jest-dom/jest-globals' to jest.setup.ts.
  2. Adding setupFilesAfterEnv: ['<rootDir>/tests/jest.setup.ts'], to jest.config.ts.
  3. Adding "types": ["@testing-library/jest-dom/jest-globals"] to tsconfig.ts.

or adding import "@testing-library/jest-dom" to every test file.

For me, the changes to tsconfig.json didn't fix the issue, but adding import '@testing-library/jest-dom/jest-globals' worked right away.

Here is my tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "baseUrl": "src",
    "downlevelIteration": true,
    "allowSyntheticDefaultImports": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "strictNullChecks": true,
    "typeRoots": ["./node_modules/@types"],
    "paths": {
      "ui-component": ["components/ui-component"],
      "ui-component/*": ["components/ui-component/*"],
      "components": ["components"]
    },
    "plugins": [
      {
        "name": "next"
      }
    ]
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "jest.setup.ts"],
  "exclude": ["node_modules"]
}

Here is my jest.setup.ts:

import '@testing-library/jest-dom/jest-globals';
import '@testing-library/jest-dom';

@palucdev
Copy link

Looks like cypress is also adding some expect() interfaces causing problems with the jest related types.

Adding direct expect import to the test files fixed it for me:

import { expect } from '@jest/globals';

@eeberhart40
Copy link

I've come across the issue you're experiencing and I believe I have a solution that might help you.

If you add the following line to your tsconfig.json under compilerOptions:

{
  "compilerOptions": {
    // ... other options
    "types": ["@testing-library/jest-dom"],
    // ... other options
  }
}

This will inform TypeScript to include the type definitions from @testing-library/jest-dom, which should resolve the type errors you're seeing.

this worked!

@shiwenyu
Copy link

shiwenyu commented Aug 9, 2024

  1. check your @testing-library/js-dom version, somer version don't contain ts file, eg. 5.16.4. If not, please update @testing-library/js-dom version to 6.x.
  2. add blow code to your tsconfig "types": [ "jest", "@testing-library/jest-dom"]

hellofanny added a commit to vtex/faststore that referenced this issue Sep 12, 2024
## What's the purpose of this pull request?

- Setup `@testing-library/jest-dom` to help to test our components when
checking an element's attributes, its text content, its css classes...
- Adds `Card` component tests
- Introduces accessibility tests: This won't guarantee that what we're
building is accessible, but it's a first step towards it. 🥳
- Updates `CheckboxField` component test 

TODO: Document 

## How it works?

Currently, our components library do not have tests, but we want to
introduce them for upcoming components. For existing components, we will
gradually add tests retroactively.

## How to test it?

1. navigate to `packages/components` -> run `yarn install`
2. run `yarn test`, you will be able to see the tests running
<img width="873" alt="image"
src="https://github.com/user-attachments/assets/1e4c0fcc-4ded-45c5-a078-0fad99c52dba">

_____

3. removing `<Label>` component from `CheckboxField`, when running the
step 2, you will get:
<img width="1005" alt="image"
src="https://github.com/user-attachments/assets/898360ba-2a9a-40d5-afd4-a6c0f74d11a4">


## References

https://testing-library.com/docs/ecosystem-jest-dom
testing-library/jest-dom#546
NickColley/jest-axe#79
@estevan-ulian
Copy link

In my project I use vitest and cypress, so cypress started overwriting the vitest types. To solve this problem, I added it to my tsconfig.json:
... "exclude": ["node_modules", "./cypress.config.ts", "cypress"] ...

See more: https://stackoverflow.com/questions/58999086/cypress-causing-type-errors-in-jest-assertions

@joekrill
Copy link

I've always found using the types config option in tsconfig.json problematic. Adding this to my setupTests.js (or whatever equivalent you have) also works, without introducing the additional issues with setting the types option:

/// <reference types="@testing-library/jest-dom" />

@admansour
Copy link

This fixed my problem.

import {expect, jest, test} from '@jest/globals';

You may read about it in the Jest docs
https://jestjs.io/docs/expect

@DiegoLibonati
Copy link

I fix this in the next way:

tsconfig.json i had:

"exclude": ["node_modules", "**/*.test.ts"]

i changed to:

"exclude": ["node_modules"]

And this change fix my problem.

tsconfig.json working file:

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "esModuleInterop": true,

    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "types": ["node", "jest", "@testing-library/jest-dom"]
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}

In my jest.setup.ts file, i had this line:

import "@testing-library/jest-dom";

Example on working test with my solution:

import { getByClassName } from "./getByClassName";

const INITIAL_HTML = `
    <main>
        <section>
            <article class="test1" />
            <article class="test2" />
            <article class="test3" />
        </section>
    </main>
`;

const EXISTING_CLASS = "test2";
const NO_EXISTING_CLASS = "test4";

beforeEach(() => {
  document.body.innerHTML = INITIAL_HTML;
});

afterEach(() => {
  document.body.innerHTML = "";
});

test("It must return an html element with a specific class and a specific role.", () => {
  const element = getByClassName("article", EXISTING_CLASS);

  expect(element).toBeTruthy();
  expect(element).toBeInTheDocument();
  expect(element).toHaveClass(EXISTING_CLASS);
});

test("It Must NOT return an html element, must return null.", () => {
  const element = getByClassName("article", NO_EXISTING_CLASS);

  expect(element).toBe(null);
  expect(element).toBeFalsy();
  expect(element).not.toBeInTheDocument();
});

@Yimiprod
Copy link

Yimiprod commented Nov 14, 2024

Just found out that adding @testing-library/jest-dom in tsconfig.ts types has a flaw:
It overload the type definition of HTMLInputElement type.

import { type InputHTMLAttributes } from 'react';

interface Props extends InputHTMLAttributes<HTMLInputElement> {
  label: string
}

const MyInput = ({ label, ...props }: Props) => {
  return (
    <div>
      <label>{label}</label>
      <input {...props} />
    </div>
  );
}

Also using typeRoot make it not works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests