在赛普拉斯中导入项目模块

Nut*_*ing 5 integration-testing automated-tests typescript cypress

我想将一些常量从项目导入到测试中(例如,测试localstorage操作)。在我的IDE中使用import(或require)时不会显示错误:

在此处输入图片说明

运行赛普拉斯时,我得到: Error: Cannot find module

在此处输入图片说明

尽管不使用任何特定功能,该模块仍处于TypeScript(Config.ts)中。

我没有修改任何Command或Support脚本。但是我在Cypress文件夹中有一个tsconfig.json,以便我的Create React App可以在不与Jest冲突的情况下运行。

{
  "extends": "../tsconfig",
  "include": ["../node_modules/cypress/types", "**/*.ts"]
}
Run Code Online (Sandbox Code Playgroud)

我尝试在中添加../src../src/**/*.tsinclude但似乎没有任何效果。

我究竟做错了什么?谢谢!

Jul*_*ige 6

添加webpackcypress-webpack-preprocessorts-loader(如果尚不存在):

yarn add --dev webpack @cypress/webpack-preprocessor ts-loader
Run Code Online (Sandbox Code Playgroud)

cypress / plugins / index.js中,只需将其添加到您的配置中即可:

const wp = require('@cypress/webpack-preprocessor')

module.exports = (on) => {
  const options = {
    webpackOptions: {
      resolve: {
        extensions: [".ts", ".tsx", ".js"]
      },
      module: {
        rules: [
          {
            test: /\.tsx?$/,
            loader: "ts-loader",
            options: { transpileOnly: true }
          }
        ]
      }
    },
  }
  on('file:preprocessor', wp(options))
}
Run Code Online (Sandbox Code Playgroud)

赛普拉斯现在应该加载您的TS文件。

有关完整TS配置的更多信息:https : //basarat.gitbooks.io/typescript/docs/testing/cypress.html


tom*_*ler 5

从 2020 年 4 月和 cypress v4.4.0 开始,不再需要此设置,因为 Cypress 现在支持 typescript ootb。

基本上现在您只需要将打字稿(如果还没有)npm install typescript --save-dev添加到您的项目中,然后将一个添加tsconfig.json到您的 cypress 文件夹中,其内容与此类似:

{
  "compilerOptions": {
    "strict": true,
    "baseUrl": "../node_modules",
    "target": "es5",
    "lib": ["es5", "dom"],
    "types": ["cypress"]
  },
  "include": [
    "**/*.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)

取自并查看 https://docs.cypress.io/guides/tooling/typescript-support.html#Set-up-your-dev-environment了解更多信息。