toBeInTheDocument not working in Jest

1 min read

If you are using Jest, toBeInTheDocument does not seem to work. Google and GPT suggest a lot of things. But what works is adding an import in each test file.
import '@testing-library/jest-dom/jest-globals';
For some reason, adding it to the test setup file does not work. This has to be imported in each file.
Eg test that uses toBeInTheDocument.
import { describe, test, expect } from '@jest/globals'
import { render, screen } from '@testing-library/react'
import { Header } from '../src'
import '@testing-library/jest-dom/jest-globals'
const HEADING = 'heading'
describe('Header tests', () => {
test('Header renders', () => {
render(<Header heading={HEADING} />)
const headingElem = screen.getByText(HEADING)
expect(headingElem).toBeInTheDocument()
})
})
0
Subscribe to my newsletter
Read articles from Vijay Thirugnanam directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Vijay Thirugnanam
Vijay Thirugnanam
Engineer working in Cerebras. Latest work includes Cerebras Inference. I love writing code in React, TypeScript, C++, Python. I spend most of my work hours tinkering with code.