【问题标题】:Cypress test fails to run when importing from source code of CRA+TS app从 CRA+TS 应用程序的源代码导入时,Cypress 测试无法运行
【发布时间】:2020-06-23 14:51:24
【问题描述】:

我的一个 Cypress 测试在尝试从 create-react-app src 目录的源代码中的文件导入时无法运行。

测试看起来像:

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

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

导入的源文件如下所示:

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

Cypress 测试失败是由源目录中的 Jest 测试文件引起的:

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`.

已安装 Jest 类型定义。此外,我试图在 Cypress tsconfig 中排除有问题的 Jest 测试,但无济于事。

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

这是一个最小的repo that reproduces my problem

最后,澄清我为什么要从源目录将东西导入 Cypress 测试 - 导入的变量旨在成为 DOM 选择器或返回 DOM 选择器的函数,这样选择器就不会在测试中硬编码。

【问题讨论】:

  • 您是否考虑过在 TS 中也编写 cypress 测试?

标签: reactjs typescript create-react-app cypress


【解决方案1】:

我不确定为什么消息是 TypeScript 没有为 /my-app/src/constants.ts 发出输出,这似乎表明该文件是可读的,并且 typescript 试图解析它,并且不识别语法。

但我的猜测是测试代码在浏览器进程中运行,无法访问其文件夹之外的文件。

如果constant.tscypress/fixtures 中,它可以工作,所以一种简单的方法是添加一个脚本来复制文件。调用“cypress”脚本时,会自动运行一个名为“precypress”的脚本。

这是 90% 的情况 - 当 constants.ts 更改时,您不会重新加载热模块。

package.json

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

它也适用于函数和处理输入,

测试

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;

【讨论】:

  • 在我们的例子中,赛普拉斯在尝试运行从源代码导入的测试时会引发 webpack 编译错误。您的解决方案对我们有用,但我觉得它更像是一种解决方法,而不是实际解决问题,因为我们的测试在某个时间点运行良好。我们正在尝试移动 cypress 文件夹中的所有常量,并从那里将它们导入到源代码中。这样,热模块重新加载可能仍然有效。
猜你喜欢
  • 2021-11-27
  • 1970-01-01
  • 2023-03-04
  • 2021-05-09
  • 2020-12-04
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多