0

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.

Luís Soares
  • 5,726
  • 4
  • 39
  • 66
  • Have you tried using [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind)? – morganney Nov 16 '22 at 03:16
  • as soon as I use bind or call to change context (e.g. `jsDomInvocation.bind({equals: () => {throw Error("abc")} })()`), I get the same: `Cannot read properties of undefined (reading 'matcherHint')` – Luís Soares Nov 16 '22 at 09:21
  • I meant more like `const toHaveAccessibleName = matchers.toHaveAccessibleName.bind(matchers)`. – morganney Nov 16 '22 at 14:13
  • I tried but got the same result. I believe `this.equals` is not present at all. even if the bind was correct, I'm not sure if its code exists at all because it belongs to jest and I only have jest-dom. so first I have to find out how to bring jest functions that matter in. – Luís Soares Nov 16 '22 at 15:38

1 Answers1

0
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()