3

One of my Cypress tests fails to run when it tries to import from a file in the source code of a create-react-app src directory.

The test looks like:

// cypress/integration/this-fails.js
import { MY_CONSTANT } from '../../src/constants';

describe('Cypress', () => {
  ...
})

The imported source file looks like:

// src/constants.ts
export const MY_CONSTANT = 'foo';

The Cypress test failure is caused by a Jest test file in the source directory:

ERROR in /my-app/src/App.test.tsx(5,1)

Cannot find name 'test'. Do you need to install type definitions for a test runner? Try`npm i @types/jest`or`npm i @types/mocha`.

The Jest type definitions are installed. Additionally, to no avail, I have tried to exclude the problematic Jest test in the Cypress tsconfig.

// cypress/tsconfig.json
{
  ...
  "exclude": [
    "../src/App.test.tsx"
  ],
  ...
}

Here is a minimal repo that reproduces my problem.

Lastly, to clarify why I am importing things into Cypress tests from the source directory — the imported variable is intended to be a DOM selector or a function that returns a DOM selector so that selectors are not hardcoded in the tests.

brietsparks
  • 4,776
  • 8
  • 35
  • 69

1 Answers1

2

I'm not sure why the message is TypeScript emitted no output for /my-app/src/constants.ts, this seems to indicate that the file is readable and typescript attempts to parse it, and does not recognize the syntax.

However my guess is that the code of the test is running in a browser process and can't access files outside of it's folder.

If constant.ts is in cypress/fixtures it works, so one easy way is to add a script to copy the file. A script called "precypress" will be automatically run when the "cypress" script is invoked.

This is kind of 90% there - you don't get hot-module reload when constants.ts changes.

package.json

"scripts": {
  ...
  "precypress": "copyfiles ./src/constants.ts ./cypress/fixtures",
  "cypress": "cypress open"
},

It also works with functions and handles typing,

test

import { MY_CONSTANT, getMyConstant } from '../fixtures/src/constants';

describe('Cypress', () => {

  it('is working', () => {
    cy.visit('/')
    alert(MY_CONSTANT);
    alert(getMyConstant());
    expect(true).to.equal(true)
  })
})

constant.ts

export const MY_CONSTANT: Number = 10;

export const getMyConstant: Function = () => 20;
Richard Matsen
  • 20,671
  • 3
  • 43
  • 77
  • In our case, Cypress throws a webpack compilation error when trying to run a test that imports from source code. Your solution worked for us, however I feel it's more like a workaround than actually solving the problem, since our tests were working fine at some point back in time. We are trying to move all the constants in the cypress folder, and import them in the source code from there. That way, the hot-module reload might still work. – Ovidiu Cristescu Aug 06 '21 at 05:38