ESLint: 'cy' is not defined (Cypress)

ReactjsEslintCypress

Reactjs Problem Overview


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!

Reactjs Solutions


Solution 1 - Reactjs

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"
  ]
},

Solution 2 - Reactjs

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

Solution 3 - Reactjs

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

Solution 4 - Reactjs

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

Solution 5 - Reactjs

The Cypress ESLint plugin will get rid of these warnings:

{
    "plugins": ["cypress"],
    "extends": ["plugin:cypress/recommended"],
    "rules": {
        "jest/expect-expect": "off"
    }
}

Solution 6 - Reactjs

at the top of your file put

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

or download the official types

source: official cypress intellisense docs

Solution 7 - Reactjs

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

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

This adds support for cypress types.

Solution 8 - Reactjs

I struggled a lot then this helped...
by adding same line in two files, eslintrc.json and eslintrc.js
(if u have other dependencies in extends just append it)

extends: ['plugin:cypress/recommended'],

Solution 9 - Reactjs

/* global cy */

import above in your test file

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

Solution 10 - Reactjs

add this to jest.config.js

  testPathIgnorePatterns: [
    '/cypress',
  ],

Solution 11 - Reactjs

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonathan TuzmanView Question on Stackoverflow
Solution 1 - ReactjsalexView Answer on Stackoverflow
Solution 2 - ReactjsOmerView Answer on Stackoverflow
Solution 3 - ReactjsAdam CaronView Answer on Stackoverflow
Solution 4 - ReactjsNoah FrancoView Answer on Stackoverflow
Solution 5 - ReactjscorysimmonsView Answer on Stackoverflow
Solution 6 - ReactjsvoiysView Answer on Stackoverflow
Solution 7 - ReactjsadrisonsView Answer on Stackoverflow
Solution 8 - ReactjsCodeWorldView Answer on Stackoverflow
Solution 9 - ReactjshaxoraView Answer on Stackoverflow
Solution 10 - ReactjsAjonesView Answer on Stackoverflow
Solution 11 - ReactjsRon NewcombView Answer on Stackoverflow