If you’re working with Cypress and Jest in the same project, TypeScript may throw errors that the standard Jest assertions are not valid types on the Assertion
class.
The error I get looks like this:
FAIL src/service/sort-by-options.test.ts
● Test suite failed to run
src/service/sort-by-options.test.ts:5:29 - error TS2551: Property 'toEqual' does not exist on type 'Assertion'. Did you mean 'equal'?
5 expect(sortByOptions()).toEqual(initialOptions);
~~~~~~~
node_modules/cypress/types/chai/index.d.ts:206:9
206 equal: Equal;
~~~~~
'equal' is declared here.
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.065 s
Ran all test suites.
Code language: JavaScript (javascript)
Though in the IDE, even before running the tests, you will likely see something like this:
This is a pretty easy fix thankfully.
What we need is two tsconfig.json
files in our project.
One for our project’s root directory, and another for Cypress.
Here’s an example of my ‘fixed’ root tsconfig.json
:
// {root}/tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
// stuff removed for brevity
},
"include": ["**/*.ts"],
"exclude": ["node_modules","cypress","cypress.config.ts"]
}
Code language: JSON / JSON with Comments (json)
The key entry here is actually cypress
, which is the directory name for my Cypress tests. Update yours to match whatever name you give your Cypress tests dir.
OK, not done yet.
You will also need to add in a second tsconfig.json
in the root of your Cypress directory.
As above, mine is ./cypress
, but adapt accordingly.
This one can / may / will be different to your root directory tsconfig.json
. This is a completely different config that can be changed however you need.
As an example:
// {root}/cypress/tsconfig.json
{
"compilerOptions": {
"target": "es5",
"noEmit": true,
"lib": ["es5", "dom"],
"types": ["cypress",
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["**/*.ts"]
}
Code language: JSON / JSON with Comments (json)
But that really is just an example. If in doubt, copy yours from your root, but remember to remove the cypress excludes.
After that, you should find Jest far happier:
PASS src/service/sort-by-options.test.ts
service/sort-by-options
✓ should return all the initial options if no selection is given (3 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.026 s
Ran all test suites.
Watch Usage: Press w to show more.
Code language: JavaScript (javascript)
Lovely.