jest-dom icon indicating copy to clipboard operation
jest-dom copied to clipboard

Upgrading to v6.0.0 remove the `toBeInTheDocument` interface with vitest

Open qchuchu opened this issue 10 months ago • 34 comments

  • @testing-library/jest-dom version: 6.0.0
  • node version: 18.16
  • npm (or yarn) version: 9.5.1

Relevant code or config:

import '@testing-library/jest-dom/vitest';
import { vitest } from 'vitest';
  await waitFor(() => {
    expect(getByTestId('text-input-error-message')).toBeInTheDocument();
  });

What you did:

Upgraded from v5 to v6

What happened:

image

I don't know why, but upgrading the package to the last version using vitest caused all my "toBeInTheDocument" matchers to be undefined, although I can see them in the type definition of the package.

Reproduction:

TO-DO

Problem description:

  • All my tests are failing because toBeInTheDocument is not defined anymore

Suggested solution:

I guess this is due to an upgrade on the dependency of jest types but I'm not sure. Still digging.

qchuchu avatar Aug 17 '23 13:08 qchuchu

What version of vitest, and where is the import statement located for @testing-library/jest-dom/vitest?

jgoz avatar Aug 17 '23 14:08 jgoz

fwiw this is happening to me in Jest too.

curtvict avatar Aug 17 '23 16:08 curtvict

ah sorry I thought that I added the vitest version.

Vitest -> 0.34.2

I added the import statement in the vitest.setup.ts file (that is pointed from my vite.config.ts like this)

/// <reference types="vitest" />

import react from '@vitejs/plugin-react-swc';
import { defineConfig } from 'vite';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: ['test/vitest.setup.ts'],
    include: ['**/?(*.)test.ts?(x)'],
  },
});

qchuchu avatar Aug 17 '23 18:08 qchuchu

@qchuchu Have you added test/vitest.setup.ts to your tsconfig.json file? You might also need to add the global vitest types reference to that file.

test/vitest.setup.ts:

/// <reference types="vitest" />

import '@testing-library/jest-dom/vitest`;

tsconfig.json

{
  "compilerOptions": {},
  "include": ["src", "test/vitest.setup.ts"]
}

jgoz avatar Aug 17 '23 19:08 jgoz

So it does work by adding the setup file in the tsconfig.json, but only if I stay with the original configuration

test/vitest.setup.ts

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

If I add /vitest at the end, i'm facing the issue again.

qchuchu avatar Aug 17 '23 19:08 qchuchu

Hmm, I think that's because you're using Vitest in "globals" mode. There isn't really a difference between what you have now and using /vitest, which was designed for the default non-globals mode, so if this works for you I say go with it.

jgoz avatar Aug 17 '23 20:08 jgoz

Getting this error trying to import

// setup.ts
import matchers from '@testing-library/jest-dom/vitest';

Error:

File '/Users/x/y/node_modules/@testing-library/jest-dom/vitest.d.ts' is not a module.ts(2306)

Meemaw avatar Aug 18 '23 06:08 Meemaw

is adding the setup file to the tsconfig the only way to get this to work? I'm using a monorepo where the vitest config is created in a separate package and the consuming applications/libraries have it like this in their vitest.config.ts

import {defineVitestConfig} from 'shared-workspace-vitest-setup';
export default defineVitestConfig({
  // custom options here that get merged with the default config
  // default config contains a setupFile adding dom matchers
});

i don't really want to add something like ../../packages/vitest-config/setupFile.js to every package tsconfig just for this, if that even works because the file is outside of the tsconfig parent dir....

edit: Instead of including the setup file in the tsconfig, you can reference it directly in tsconfig compilerOptions.types

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

or put it in a .d.ts file that's included like src/jest-dom-types.d.ts

/// <reference types="@testing-library/jest-dom/vitest.d.ts" />

dominikg avatar Aug 18 '23 09:08 dominikg

Getting this error trying to import


// setup.ts

import matchers from '@testing-library/jest-dom/vitest';

Error:


File '/Users/x/y/node_modules/@testing-library/jest-dom/vitest.d.ts' is not a module.ts(2306)

Matchers are not exported from the vitest export. If you want to import matchers, use this:

import * as matchers from '@testing-library/jest-dom/matchers'

Or if you want to automatically extend Vitest's expect, do this:

import '@testing-library/jest-dom/vitest'

jgoz avatar Aug 18 '23 15:08 jgoz

@dominikg Thanks for pointing out the alternate ways of getting the types recognized by TS. We should probably add that to the readme.

jgoz avatar Aug 18 '23 15:08 jgoz

fwiw this is happening to me in Jest too.

I can also confirm this is also happening with Jest as well. Don't know how to handle those errors yet :(

DeveloperMatheus avatar Aug 21 '23 08:08 DeveloperMatheus

For those using Jest, make sure you are importing like this:

import '@testing-library/jest-dom'

Many people are using an older deprecated /extend-expect import that was removed in v6.

jgoz avatar Aug 21 '23 14:08 jgoz

Thanks @jgoz I can confirm this fixes the issue for me.

curtvict avatar Aug 21 '23 16:08 curtvict

@jgoz Sorry for asking help in this issue, i was checking my setup files and i see that i'm importing almost the same way as the library's documentation:

I have a .setup folder that groups some mocks globally, and also the import '@testing-library/jest-dom. This is my setupFilesAfterEnv property in jest.config.js: setupFilesAfterEnv: ['<rootDir>/.jest/setup.ts']

You have any suggestion of what might be causing my errors? When i'm importing on each test, the errors goes away (of course this is a solution, but would be better for me importing this globally in the setup hehe)

EDIT:

I found one possible solution, in my case, i tried to create e second setup file outside this folder (just in the root dir normally), and mentioned in the jest config file, and it worked! But, following my old setup file, can't it be inside any folder anymore?

DeveloperMatheus avatar Aug 23 '23 08:08 DeveloperMatheus

@DeveloperMatheus Is your setup file included in tsconfig.json? Like, in the includes or files properties?

jgoz avatar Aug 23 '23 15:08 jgoz

@jgoz It's like this:

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "~/*": ["*"]
    },
    "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": false
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

It doesn't have the files property

EDIT: My setup file is linked in my jest.config.js

DeveloperMatheus avatar Aug 24 '23 10:08 DeveloperMatheus

@DeveloperMatheus it might be because your setup file is in a .jest folder. Typescript might not automatically include files in dot-folders even if they match an include pattern. Try creating a files property next to include and explicitly list the setup file:

"include": [...],
"files": [".jest/setup.ts"]

jgoz avatar Aug 24 '23 14:08 jgoz

@jgoz Many many many thanks for your help! It worked!

DeveloperMatheus avatar Aug 25 '23 11:08 DeveloperMatheus

I think depending on how you import expect may cause this issue to occur. For instance my import looks like

import { expect } from 'vitest';

and below is a SS of what the type def points to image

instead of the above if I do image then typescript finds the functions defined by jest-dom. Not sure if both need to be defined depending on how expect is being imported by the user?

kalvenschraut avatar Sep 01 '23 20:09 kalvenschraut

So while adding import '@testing-library/jest-dom'; to my setup for vitest (0.34.3) does prevent TS from giving an error, removing it gives me a slightly different error:

Property  toBeInTheDocument  does not exist on type  Assertion<HTMLElement>

ajnozari avatar Sep 04 '23 05:09 ajnozari

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

jgoz avatar Sep 04 '23 06:09 jgoz

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

This is my current setupTests.ts

import '@testing-library/jest-dom';
import '@testing-library/jest-dom/vitest';
import createFetchMock from 'vitest-fetch-mock';
import { afterEach, vi } from 'vitest';
import { cleanup } from '@testing-library/react';

export const fetchMocker = createFetchMock(vi);
fetchMocker.enableMocks();

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

I've tried with both import '@testing-library/jest-dom/vitest'; and import '@testing-library/jest-dom'; and JUST import '@testing-library/jest-dom/vitest'; alone.

I'm starting to think it might be something to do with yarn PnP and WebStorm. I have updated TS, ensured I only import /vitest and my IDE still shows errors.

Interestingly the tests still pass despite the error.

ajnozari avatar Sep 04 '23 18:09 ajnozari

And setupTests.ts is included in your tsconfig.json file, either via include or files?

jgoz avatar Sep 05 '23 00:09 jgoz

Also using pnpm, I'm getting the type error Property  toBeInTheDocument  does not exist on type  Assertion<HTMLElement> .

The tests pass, but still get the typescript error when typechecking.

test/setup-test-env.ts:

import { installGlobals } from '@remix-run/node';
import '@testing-library/jest-dom/vitest';

installGlobals();

tsconfig includes test/setup-test-env.ts explicitly

tsconfig:

{
  "include": ["remix.env.d.ts", "**/*.ts", "**/*.tsx", "test/setup-test-env.ts"],
  "compilerOptions": {
    "lib": ["DOM", "DOM.Iterable", "ES2019"],
    "isolatedModules": true,
    "esModuleInterop": true,
    "jsx": "react-jsx",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "target": "ES2019",
    "strict": true,
    "allowJs": true,
    "forceConsistentCasingInFileNames": true,
    "baseUrl": ".",
    "paths": {
      "~/*": ["./app/*"]
    },
    "types": ["vitest/globals"],

    // Remix takes care of building everything in `remix build`.
    "noEmit": true
  }
}

image

justinwaite avatar Sep 06 '23 18:09 justinwaite

Hey guys, I also ran into the same issue but finally got a working setup with v6.1.3, vitest 0.34.6 and pnpm. I have a React project created by Vite.

My setup:

// src/__tests__/extend-expect.ts
import "@testing-library/jest-dom/vitest";

Remember to add the above to vite.config.ts setupFiles.

// src/vitest.d.ts
import { type TestingLibraryMatchers } from "@testing-library/jest-dom/matchers";
import {
  type Assertion,
  type AsymmetricMatchersContaining,
  type expect,
} from "vitest";

type CustomMatchers<R = unknown> = TestingLibraryMatchers<
  ReturnType<typeof expect.stringContaining>,
  R
>;

declare module "vitest" {
  interface Assertion<T = unknown> extends CustomMatchers<T> {}
  interface AsymmetricMatchersContaining extends CustomMatchers {}
}

For tsconfig.json, there were no additional changes. I did not add the extend-expect file into include (Vite already added src dir).

I think the problem is that the types being shipped for @testing-library/jest-dom/vitest just doesn't match with Vitest's own official docs of how to extend the types.

dteoh avatar Oct 06 '23 01:10 dteoh

To make it work if you are using the vitest:

  1. Make sure you have installed @testing-library/jest-dom
  2. Create the setupTests.ts file with content inside import '@testing-library/jest-dom/vitest'
  3. Import the setupTests.ts file inside vitest.config.ts, for example: setupFiles: path.resolve(__dirname, '../../setupTests.ts'),
  4. Add "files": ["../../setupTests.ts"] into the tsconfig.json file

Ridd0 avatar Oct 10 '23 12:10 Ridd0

So it does work by adding the setup file in the tsconfig.json, but only if I stay with the original configuration

test/vitest.setup.ts

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

If I add /vitest at the end, i'm facing the issue again.

Had the same issue and can confirm this. When having "globals" set to true (in vite.config.ts), I need to import from @testing-library/jest-dom instead of @testing-library/jest-dom/vitest to make TypeScript happy.

But after taking a look into docs from vitest config for globals, I saw that you need to add vitest/globals to compilerOptions\types property. I did not had that and added it now. With that the import from @testing-library/jest-dom/vitest works without troubles

nwi-di avatar Oct 12 '23 05:10 nwi-di

So it does work by adding the setup file in the tsconfig.json, but only if I stay with the original configuration test/vitest.setup.ts

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

If I add /vitest at the end, i'm facing the issue again.

Had the same issue and can confirm this. When having "globals" set to true (in vite.config.ts), I need to import from @testing-library/jest-dom instead of @testing-library/jest-dom/vitest to make TypeScript happy.

But after taking a look into docs from vitest config for globals, I saw that you need to add vitest/globals to compilerOptions\types property. I did not had that and added it now. With that the import from @testing-library/jest-dom/vitest works without troubles

Thank you!! I can confirm this also worked for me!

mdodge-ecgrow avatar Oct 26 '23 16:10 mdodge-ecgrow

Just bumped in this issue. For me, after following the setup instructions found on the testing-library docs, I also had to add jsdom types: npm i -D @types/testing-library__jest-dom, then it worked.

matchatype avatar Dec 11 '23 14:12 matchatype

create a setupTest.ts file in src folder and add import '@testing-library/jest-dom'

In vitest.config.ts file

import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: ['./src/setupTests.ts'],
    coverage: {
      provider: 'v8'
    }
  }
})

And finally install types/testing-library. This worked for me

vnaykvkrm avatar Feb 09 '24 05:02 vnaykvkrm