Using Jest matchers in Cypress
It all started when I was mentioned an a Twitter conversation…
Is it possible to use Jest’s expect while using Cypress? Sure.
I haven’t used Jest before, but I’ve heard good things. After playing around, I found out Jest publishes the expectation library directly on npm under the package name
expect. So I wanted to find out if that would work. Turns out it does.
I even went a bit further to see what it would take to use Cypress’s short-hand syntax using string matchers. Turns out that works as well:
This technique could also be applied to using Jasmine’s
expect as well.
The expectation library isn’t being replaced, so standard Cypress commands will work.
While it is possible, I don’t recommend it. The Cypress team did a lot of work ensuring assertions work correctly in the Log interface and are inspectable through the console when assertions are clicked on. My examples don’t do any of that. If the assertion is a success, nothing is logged. If it is an error, Cypress’ error catching will output the error. The error from Jest’s message handling is still readable:
CypressError: Timed out retrying: expect(object).toHaveProperty(path, value)
Expected the object:
To have a nested property:
With a value of: