reactjstypescriptjestjsvitevitest

toBeInTheDocument Matcher Not Working in Vitest with @testing-library/jest-dom


I’m having trouble using the toBeInTheDocument matcher with Vitest and @testing-library/jest-dom in my TypeScript project. Even though I have installed and configured everything correctly, I’m still getting the error:

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

Project Setup:

Steps Taken So Far: Installed necessary packages:

npm install --save-dev vitest @testing-library/react @testing-library/jest-dom

Updated tsconfig.json to include global types for Vitest and Jest DOM:

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

Created a global types file (types.d.ts) to extend Vitest matchers with Jest DOM matchers:

/// <reference types="vitest" />
import '@testing-library/jest-dom';

declare global {
  namespace Vi {
    interface Matchers<R> extends jest.Matchers<R> {}
  }
}

Configured vite.config.ts to include global test settings:

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

export default defineConfig({
  plugins: [react()],
  test: {
    globals: true, 
    environment: 'jsdom', 
    setupFiles: './vitest.setup.ts', 
  },
});

Set up vitest.setup.ts to import @testing-library/jest-dom:

import '@testing-library/jest-dom';
Test File (App.test.tsx):

import { render, screen } from '@testing-library/react';

const App = () => <h1>Hello, Vitest!</h1>;

test('renders the heading', () => {
  render(<App />);
  expect(screen.getByText('Hello, Vitest!')).toBeInTheDocument();
});

Error: Despite following the configuration steps above, I’m still getting the following TypeScript error:

Property 'toBeInTheDocument' does not exist on type 'JestMatchers'.

Other Details:

I’ve also tried adding import { expect } from 'vitest' in my test files, but the error persists. I’m using Vitest as my test runner, not Jest. The tests run successfully (the test passes), but I keep encountering this type-checking issue.

What I’ve Tried:

Can anyone help me figure out why toBeInTheDocument isn’t recognized as a valid matcher? Any insight or suggestions would be greatly appreciated!


Solution

  • Try using setup file. In jest.config.ts:

    setupFilesAfterEnv: [
      '<rootDir>/path/to/setupTests.ts',
    ],
    

    In setupTests.ts:

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