How to use jest-dom as standalone in a webpage?

195 Views Asked by At

I want to use/run jest-dom matchers separately/standalone (not in a test, but in a webpage) like this:

import matchers from '@testing-library/jest-dom/matchers'
window.matchers = matches

This is what jest-dom GitHub claims:

The intention is to make this available to be used independently of these other libraries, and also to make it more clear that these other libraries are independent from jest, and can be used with other tests runners as well.

Btw, this is why I want to do it.

Then I run webpack command and load the auto-generated JS file (at dist) into a page.

Finally, in the page, I run this:

console.log(matchers.toBeDisabled(someElem))

it works perfectly. however, as soon as I run a matcher that receives an arg, it fails. e.g.:

console.log(matchers.toHaveAccessibleName(someElem, "name 1"))

it fails with:

this.equals is not a function

after hours of reading, I understand the reason. that function is provided by Jest's expect package and it's passed as context. ok, but how can I have it available?

There's a similar question but it's a TypeScript error.

1

There are 1 best solutions below

6
On
import { expect } from 'expect'
import TestingLibraryMatchers from '@testing-library/dom/matchers.js'

expect.extend(TestingLibraryMatchers)

globalThis.expect = expect

Bundle this as an ESM or IIFE and then you can use it like

expect(someElement).toBeDisabled()