testing-library / jest-dom

:owl: Custom jest matchers to test the state of the DOM

Home Page:https://testing-library.com/docs/ecosystem-jest-dom

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using jest-dom in vite setup with nx can't resolve typescript types.

shubhamdeol opened this issue · comments

  • @testing-library/jest-dom version: 6.1.4
  • node version: 20.3.1
  • vitest version:~0.32.0
  • npm version: 9.6.7

Relevant code or config:

vitest-setup.ts

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

tsConfig include

"include": [
    "src/**/*.js",
    "src/**/*.jsx",
    "src/**/*.ts",
    "src/**/*.tsx",
  ]
Screenshot 2023-10-23 at 5 14 51 PM

Problem description:

I am using vite with nx setup. I am trying to use jest-dom. Tests is running fine. But I am not able to resolve typescript type.
I have followed the doc properly.

I've just run into the same issue of not having the vitest expect types include the jest-dom matchers, but in my case it was when using yarn with the pnpm nodeLinker.

What I found after investigation was that I needed to add @vitest/expect to my project's devDependencies for the types provided by @testing-library/jest-dom/vitest to work properly.

My investigations:

  • I tried copying the type augmentation from @testing-library/jest-dom/vitest into one of my test files, and typescript complained that the module @vitest/expect didn't exist even though it had been installed by other libs.
  • Yarn pnpm only symlinks the dependencies that you declare in your package.json file in the top-level/project's node_modules directory. Any dependencies for other modules are only linked inside their local node_modules and not available for you to import into your own project files.
  • This meant that while other vitest libs pulled in @vitest/expect as a dependency, it wasn't available at the top level node_modules directory.
  • The consequence was that the type augmentation in @testing-library/jest-dom/vitest.d.ts wasn't able to be applied to the @vitest/expect module - there wasn't a node_modules/@vitest/expect directory representing the module to be augmented.

By adding the devDependency for @vitest/expect to my package.json file, it was then linked in my project's node_modules directory allowing the types shipped with @testing-library/jest-dom/vitest to find the @vitest/expect package types to be updated.

@dawnmist Thanks for this 🙌