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:
- Testing Library: @testing-library/react, @testing-library/jest-dom
- Test Framework: Vitest
- TypeScript Version: ~5.6.2
- Vite Version: ^5.4.10
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:
- Reinstalling all dependencies (rm -rf node_modules && npm install).
Ensuring correct versions of @testing-library/jest-dom and other
dependencies. - Adding expect imports explicitly to my tests. Restarting my editor
and TypeScript server.
Can anyone help me figure out why toBeInTheDocument isn’t recognized as a valid matcher? Any insight or suggestions would be greatly appreciated!
Try using setup file
In jest.config.ts
setupFilesAfterEnv: [
'<rootDir>/path/to/setupTests.ts',
],
In setupTests.ts
import '@testing-library/jest-dom';
beloyar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.