Cypress causing type errors in jest assertions

Solution 1:

I ran into this problem yesterday. It seems that what you are saying is correct, cypress and jest both declares types for expect. In this case the cypress declaration seem to be the one that is picked up. Here's an issue from the cypress repo regarding this:

https://github.com/cypress-io/cypress/issues/1603

The solution mentioned in there worked for me. You need to exclude the jest spec files from in tsconfig.json and then declare a tsconfig.spec.json where they are explicitly included again.

tsconfig.json:

{
  ...,
  "exclude": [
    "**/*.spec.ts"
  ]
}

tsconfig.spec.json:

{
  "extends": "./tsconfig.json",
  "include": [
    "**/*.spec.ts"
  ],
  ...
}

With this in place, both my (angular 8) app compiles fine and I can run the jest tests without issue. Here's another example mentioned in the issue with a similar fix being implemented:

https://github.com/neiltownsley/react-typescript-cypress/pull/1/files#diff-e5e546dd2eb0351f813d63d1b39dbc48R29

Solution 2:

There is an official Cypress repo that shows how to fix this exact problem https://github.com/cypress-io/cypress-and-jest-typescript-example

I wasn't able to get that method to work in one of my projects, so I am using this as a workaround:

import { expect } from '@jest/globals';

Solution 3:

This worked for me in my tsconfig.json

I had to add

  "include": ["src/**/*"],

Complete code here

{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "commonjs",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "allowSyntheticDefaultImports" : true,
    "esModuleInterop" : true,
    "sourceMap": true,
    "experimentalDecorators": true
  },
  "include": ["src/**/*"],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

Solution 4:

Finally I found the solution! Just add "cypress" to the exclude property of your main tsconfig.json:

{
  ...YOUR_CONFIGS,
  "compilerOptions": {
    ...YOUR_CONFIGS,
    "typeRoots": [ // THIS TO GET ALL THE TYPES
      "node_modules/@types"
    ],
  },
  "exclude": ["cypress"], 
}

You should add also another tsconfig.json for your cypress tests. You can create a cypress folder and add that tsconfig.json there. The following is my Cypress tsconfig.json:

{
  "compilerOptions": {
    "strict": true,
    "baseUrl": "../node_modules",
    "target": "es5",
    "lib": ["es5", "dom"],
    "types": ["cypress", "@testing-library/cypress"]
  },
  "include": ["./**/*.ts"]
}