Jason Butz

Passionate about the web; enjoys JavaScript more than is probably reasonable; loves learning new things; Sr. Software Engineer @ Genesys

Custom Jest Except Matcher

October 30, 2017 in #JavaScript #Jest

Over the past week or two I've been converting a project from using RequireJS to Webpack and from using Jasmine to Jest.

One thing I ran into with while adjusting the unit tests was places where I expected mocks to get null or undefined as an argument, but I couldn't care less which it got. Jest's built in expect.any(...) and expect.anything() don't match those values, so do I hardcode which value appears to be coming through in each place? I could, but I decided a custom matcher was a better idea.

I looked at the code in Jest's expect package and more or less ripped off the expect.anything() code and adjusted it. I added that code to the file that the setupTestFrameworkScriptFile configuration value points to.

Below is what I ended up creating, I had to do a little monkeying around since Jest is written in TypeScript but everything seems to work. Feel free to make use of the matcher.

Share on Google+