jest-dom
jest-dom copied to clipboard
Include first-class typescript support for Jest's `expect` package in jest-dom
We've been experimenting with using Node.js's test runner as an alternative to Jest. It was initially added in v18 but marked as stable in v20. It's been working great for us thus far, but we have been recently started to integrate react-testing-library for component testing which works great, but there's a bit more challenge if you want to use jest-dom style matchers with expect.
jest-dom's documentation specifically calls out you can integrate with Jest-compatible expect:
If you are using a different test runner that is compatible with Jest's expect interface, it might be possible to use it with this library:
import * as matchers from '@testing-library/jest-dom/matchers' import {expect} from 'my-test-runner/expect' expect.extend(matchers)
This works exactly as expected, as long as you're using js:
import expect from 'expect'
import matchers from '@testing-library/jest-dom/matchers'
expect.extend(matchers)
However, this causes problems with Typescript as the matcher types do not include the extended type definitions.
It's reasonable to expect there wouldn't be documentation for the Node.js test runner as it's relatively new and likely not widely used. However, there's no clear indication of how to implement types correctly when using another Jest-compatible expect, such as the expect package itself.
We have a current work around (see suggested implementation below) that allows this to work correctly if we include it in our typings definition.
Describe the feature you'd like:
Include expect as an allowed alternative, similar to how vitest is implement.
Suggested implementation:
An additional import to allow for this to work as expected for both typescript and js if you're using the expect package:
import '@testing-library/jest-dom/expect'
The type should extend the expect module with Testing Library's matchers:
import type { expect } from 'expect';
import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers';
declare module 'expect' {
export interface Matchers<R extends void | Promise<void>>
extends TestingLibraryMatchers<
ReturnType<typeof expect.stringContaining>,
R
> {}
}
Describe alternatives you've considered:
N/A
Teachability, Documentation, Adoption, Migration Strategy:
If implemented, documentation could be updated to include usage patterns with expect.