繁体   English   中英

摩卡测试 TypeScript 与全局 scope 中定义的类型

[英]Mocha testing TypeScript with types defined in global scope

我目前正在为一个遗留应用程序构建一个测试框架,该应用程序有许多types.ts文件,这些文件定义了在文件顶层没有任何导入/导出的类型。 例如,我们有一个Pills/types.ts文件,其中仅包含

interface Pills {
 id: number,
 // more properties
}

根据 TypeScript 文档,如果没有导入/导出,该文件被视为一个模块,并且是全局 scope 的一部分。 任何使用Pills类型的文件都使用它而不显式导入该类型。 这目前在我们的 web 应用程序中运行良好,该应用程序作为webpack包运行。

但是,当我尝试使用在 NodeJS 上运行的mocha运行测试时,出现以下错误:

app/javascript/components/HardwareTestReports/table.tsx(18,16): error TS2304: Cannot find name 'Pill'.
app/javascript/components/HardwareTestReports/table.tsx(106,56): error TS2304: Cannot find name 'Pill'.

这是因为mocha在 NodeJS 上运行,需要文件显式声明导出/导入?

我的.tsconfig看起来像这样:

{
  "compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es7", "dom", "esnext"],
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es6",
    "jsx": "react",
    "esModuleInterop": true
  },
  "exclude": ["node_modules", "vendor", "public", "test"],
  "compileOnSave": false
}

我的 package.json 有以下测试脚本:

  "scripts": {
    "test": "TS_NODE_PROJECT='./tsconfig.json' mocha -r ts-node/register -r esm test/**/*.ts"
  },

这是因为mocha在 NodeJS 上运行,需要文件显式声明导出/导入?

重构types.ts文件以显式导入/导出它们的类型目前不是一个选项 - 我们有许多相互交织的类型,并且更新每个文件以包含导入/导出将涉及触及代码库中的几乎每个文件 - 绝对是一个长期项目处理。

假设您的tsconfig仅用于测试,您可以告诉 ts-node 包含自定义类型:

tsconfig.json

{
  "ts-node": {
    "files": true
  },
  "compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es7", "dom", "esnext"],
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es6",
    "jsx": "react",
    "esModuleInterop": true
  },
  "exclude": ["node_modules", "vendor", "public", "test"],
  "compileOnSave": false,
  "files": ["Pills/types.ts"] // WHere you keep the types
  "include": ["test/**/*.ts"] // Wherever you keep your tests
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM