Search code examples
typescriptreact-testing-libraryjest-dom

How to use jest-dom without Jest


I have a question about extending Typescript interfaces. Here is my situation:

I am using expect in my tests without Jest (I installed it separately and it works).

Now I want to use jest-dom to add the expect matchers for DOM. (they are super helpful and will make my tests easier to write).

I did the following to extend expect

import expect from 'expect'
import * as matchers from '@testing-library/jest-dom/matchers'

expect.extend(matchers)

This works and adds the matchers, but Typescript doesn't know about them.

I installed @types/testing-library/jest-dom But it didn't solve the issue.

Looking inside @types/testing-library__jest-dom I see that it extends the types of jest and not the standalone expect.

I tried adding a expect.d.ts with the following content:

import 'expect'

declare module 'expect' {
  export interface Matchers<R> {
    toBeInTheDOM(container?: HTMLElement | SVGElement): R
    // ... other methods
  }
}

But Typescript is still complaining.

Any ideas?


Solution

  • I found the solution, the following works

    import 'expect/build/types'
    
    declare module 'expect/build/types' {
      export interface Matchers<R> {
        // matchers methods here
      }
    }