Questions & Answers

How can I define Jest customer matchers inside an npm package and have them automatically be available to anyone installing said npm package?

I have a few custom matchers for jest inside a private npm package (let's call it Jesticles) that uses them. Let's call them "toHaveStatusCode" and "toHaveSamePropertiesAndValues". My npm library uses them all over the place in its internal assertions. My IDE can also see these as valid expect clauses because I have a jestSetup file that I point to from my jest config like so:

setupFilesAfterEnv: [

This npm package is the central part of a large test framework so it is consumed by dozens of other apps and services. The custom matchers work great for anything contained inside this package. However, when I consume this npm package from another runtime it says that this npm package cannot find those matchers. That's because the jest.config pointing to jestSetup.ts doesn't get evaluated in those runtimes.

The hacky garbage solution is to have a jestSetup file in every runtime that points to the Jesticle definitions, but that's unnecessary friction. Is there a way to get the published npm package to appraise these matchers properly so that you can just npm install the package and go?

2023-01-11 09:01:42
You need to load them somewhere, Jest won't trawl through the modules directory looking for things that might be matchers. Look at how jest-extended works, for example:
Answers(0) :