DEV Community

Discussion on: How To Implement Custom Matchers

Collapse
 
cyrfer profile image
John Grant

Chris, this is very helpful. I don't want to define my models (type Todo) in the same file as my jest global settings. Also, I have many test files where I need the same custom matcher. Can you describe the files used in a professional repo? What file contains declare global?

Collapse
 
angelxmoreno profile image
Angel S. Moreno

same question, any ideas @zirkelc ?

Collapse
 
zirkelc profile image
Chris Cook

Hi @angelxmoreno and @cyrfer

sorry for never responding on this topic, I seem to have forgotten about this notification. Nevertheless, I have since switched from Jest to Vitest, but the general process should be the same.

I have all my custom matchers in separate package in my monorepo, it's called lib-test and I install it in every other package that needs some test utilities like matchers or snapshot serializer. The matcher.ts file contains all custom matchers and defines the CustomMatchers interface. Here, I also add the interface to the Jest namespace (declare global { ...}) so it's available on the expect() functions.

One thing to note is, I don't use setupFilesAfterEnv in Jest config to automatically add the custom matchers. Instead, only in the test cases where I need the custom matcher, I import the toMatchTodo() from my lib-test and call expect.extend({ toMatchTodo }) at the beginning.

Because of this, the custom matcher is always available on the Jest namespace because in every test file that uses the custom matcher, the import from lib-test ensures the Jest namespace (declare global { ...}) was extended.

I hope this helps!