126

I've just started using Cypress with my React Typescript project. I've gotten some simple tests to run:

describe('settings page', () => {
  beforeEach(() => {
    cy.visit('http://localhost:3000')
  });
  it('starts in a waiting state, with no settings.', () => {
    cy.contains('Waiting for settings...')
  });
  it('shows settings once settings are received', () => {
    const state = cy.window().its('store').invoke('getState')
    console.log(state) // different question: how do I get this to be the state and not a $Chainer?
  });
});

It runs in Cypress just fine. But I get Typescript errors in Webstorm, saying that cy is not defined (a TS and ESlint error) and an error on describe saying all files must be modules when the --isolatedModules flag is provided.

I can make it a JS file instead of a TS file, then I still get cy is not defined.

I've tried import cy from 'cypress' but then I get ParseError: 'import' and 'export' may appear only with 'sourceType: module' which is a whole other can of worms (I'm taking baby steps in writing my tests and haven't had to import anything yet...)

/// <reference types="cypress" /> does not work.

Update (sort of)

I've followed instructions here and have made a little progress. To my already very full React webpack.config.dev.js I added the recommended code:

          { // TODO inserted for cypress https://stackoverflow.com/a/56693706/6826164
            rules: [
              {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
              }
            ]
          },

to the end of the list of rules (just before the file loader).

When I do this as well as setting up the plugins/index file as indicated in the article, the cypress "home screen" runs but when I click to open my tests, it takes very many seconds and then shows lots of errors, starting with

integration\settings.spec.ts
This occurred while Cypress was compiling and bundling your test code. This is usually caused by:

A missing file or dependency
A syntax error in the file or one of its dependencies
Fix the error in your code and re-run your tests.

./cypress/integration/settings.spec.ts
Module build failed (from ./node_modules/ts-loader/index.js):
Error: TypeScript emitted no output for C:\Users\...\...\front_end\cypress\integration\settings.spec.ts.
 @ multi ./cypress/integration/settings.spec.ts main[0]

Followed by, actually, a lot of Typescript output such as this:

C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx
[tsl] ERROR in C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx(37,41)
      TS2339: Property 'toBeTruthy' does not exist on type 'Assertion'.

C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx
[tsl] ERROR in C:\Users\jtuzman\dev\...\...\src\__tests__\Errors.test.tsx(41,45)
      TS2339: Property 'toBeDefined' does not exist on type 'Assertion'.

Notice that these are now errors for code outside the test files (although perhaps that makes sense). Many of them are for files in which I'm using Jest rather than Cypress, and many errors, as you can see, seem to be related to it inferring an Assertion type on expect that is not Jest, such that it thinks the toEqual matcher is wrong.

All the while, in Webstorm ESLint is still complaining about all my cy and TypeScript is underlining all those Jest assertions mentioned in the output.

This is all with a ts test file. If I rename the file to js, it says the file has no tests.

Any help? I love Cypress but I'm having a hell of a time getting it to work fully!

Jonathan Tuzman
  • 11,568
  • 18
  • 69
  • 129

14 Answers14

152

I got that error after upgrading to cypress version 4+. I installed the eslint-plugin-cypress https://github.com/cypress-io/eslint-plugin-cypress and activated it in the extends configuration either in package.json or in separate config file:

"eslintConfig": {
  "extends": [
    "plugin:cypress/recommended"
  ]
},
alex
  • 1,999
  • 3
  • 16
  • 18
94

Add .eslintrc.json to cypress directory

In .eslintrc.json

{
  "extends": [
    "plugin:cypress/recommended"
  ]
}

enter image description here

  • I do not install eslint-plugin-cypress, and it fix the problem
Omer
  • 3,232
  • 1
  • 19
  • 19
  • 10
    You need to install the plugin. The reason it looks like the problem is fixed is because ESLint will error out and stop linting the directory so all the warnings disappear. It looks like you're using VSCode, so you can click the ESLint tab in the bottom right to verify this. – CudB Jun 09 '20 at 22:13
  • Still I get this error Module build failed (from ./node_modules/cypress-plugin-tab/src/index.js): ReferenceError: Cypress is not defined – Ashok kumar Ganesan Feb 17 '21 at 12:35
  • Can you look at this [question](https://github.com/Shelex/cypress-allure-plugin/issues/49) – Ashok kumar Ganesan Feb 22 '21 at 06:13
  • Doesn't work ERROR in [eslint] Failed to load plugin 'cypress' declared in '.eslintrc': Cannot find module 'eslint-plugin-cypress' – Nikolay Advolodkin Sep 30 '22 at 13:40
25

Specify cy in eslintrc globals

Answered here

cy is a global variable. Much like location. So really it is window.cy. You can add it to the globals in Eslint. Don't import cy from cypress.

{
  "globals": {
    "cy": true
  }
}

Added that to my .eslintrc and fixed the issue

Adam Caron
  • 371
  • 3
  • 7
12

The Cypress ESLint plugin will get rid of these warnings:

{
    "plugins": ["cypress"],
    "extends": ["plugin:cypress/recommended"],
    "rules": {
        "jest/expect-expect": "off"
    }
}
corysimmons
  • 7,296
  • 4
  • 57
  • 65
12

I struggled a lot then this helped...
by adding this one line in either of two config files, eslintrc.json or eslintrc.js
(if u have other dependencies in extends, append them as well after it)

extends: ['plugin:cypress/recommended'],
CodeWorld
  • 2,017
  • 1
  • 11
  • 21
10

Try.. import cy from "cypress" this solved the problem for me.

Noah Franco
  • 139
  • 1
  • 6
  • 4
    Hi, welcome to stack-overflow . you can use this link for improve your answer https://stackoverflow.com/help/how-to-answer and https://stackoverflow.com/tour – Amirhossein Apr 24 '20 at 04:08
8

at the top of your file put

/// <reference types="cypress" />

or download the official types

source: official cypress intellisense docs

voiys
  • 269
  • 5
  • 14
  • 2
    Thanks but that's actually not working at all. I also tried downloading @types/cypress and adding it to my tsconfig, and that doesn't help any of the problems. – Jonathan Tuzman Nov 21 '19 at 20:25
  • Still I get this error Module build failed (from ./node_modules/cypress-plugin-tab/src/index.js): ReferenceError: Cypress is not defined – Ashok kumar Ganesan Feb 17 '21 at 12:30
4

Just add these lines to your tsconfig.json file for e2e tests:

"compilerOptions": {
    "types": ["cypress"]
}

This adds support for cypress types.

adrisons
  • 3,443
  • 3
  • 32
  • 48
2
/* global cy */

import above in your test file

example: suppose you have login test ("cypress test file ex: cypress/integration/login.js")

haxora
  • 81
  • 6
2

I replaced the old style of type referencing,

/// <reference types="cypress" />

with this silly import

import type {} from 'cypress';

And the IDE now both recognizes Cypress's globals while also avoiding the "isolatedModules" issue it has with tsconfig.json

Ron Newcomb
  • 2,886
  • 21
  • 24
1

Seems I found a remedy that works (at least) for me. Adding this import to the top of the test:

import _Cypress from "cypress";

relaxes and comforts the ESLint plugin. Actually any name for the import can be used instead of "_Cypress": any that conforms your sense of beauty, does not conflict with anything and starts with underscore (to not provoke ESLint again). Of course, it looks like a kind of voodoo. I don't know why it works and probably there are better ways to present ESLint Cypress's globals, but I don't know them.

1

For me adding .eslintignore in root directory and placing *.cy.js for all my test files was only workaround.

It seems that for the rest of us the working solution really is installing eslint-plugin-cypress and adding:

"eslintConfig": {
  "extends": [
    "plugin:cypress/recommended"
  ]
},

but idt didn't helped in my case because this plugin is no longer supported (almost for a year now) so it ended with critical error when combined with cypress-axe.

Michael
  • 23
  • 4
0

add this to jest.config.js

  testPathIgnorePatterns: [
    '/cypress',
  ],
Ajones
  • 1
0

Wrap your config object with defineConfig in the cypress.confi.ts file like so

import { defineConfig } from "cypress";

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // implement node event listeners here
      return config;
    },
  },

  component: {
    devServer: {
      framework: "create-react-app",
      bundler: "webpack",
    },
  },
});
Gwamaka Charles
  • 1,479
  • 9
  • 12