Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress test fails to run when importing from source code of CRA+TS app

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.

like image 688
brietsparks Avatar asked Nov 26 '25 11:11

brietsparks


1 Answers

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;
like image 172
Richard Matsen Avatar answered Nov 29 '25 00:11

Richard Matsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!