如何在 mocha 测试中使用 TypeScript 声明文件?

Rob*_*mba 6 mocha.js node.js typescript typescript-typings ts-node

我有一个 TypeScript 项目,其中的测试是用 TypeScript 编写的。我想用来mocha直接测试TS文件。我为此使用了 ts-node,如ts-node#mocha 中所述。在项目中,我使用了一个没有 TS 类型定义的 JS 库。所以我d.ts为此创建了一个文件。编译和运行项目时一切正常。但是摩卡咖啡失败了:

% yarn mocha --require ts-node/register --require source-map-support/register ./test/*.ts 

src/client.ts:3:26 - error TS7016: Could not find a declaration file for module 'algosdk'. '/home/robert/projects/algorand/ts-mocha/node_modules/algosdk/index.js' implicitly has an 'any' type.
  Try `npm install @types/algosdk` if it exists or add a new declaration (.d.ts) file containing `declare module 'algosdk';`

3 import * as algosdk from "algosdk";
Run Code Online (Sandbox Code Playgroud)

看来 ts-node 无法识别这些d.ts文件。

唯一有效的解决方案是使用require而不是import语句,但这不会将类型链接到 algosdk。

如何将 mocha 与 TS 文件和类型定义文件一起使用?

这是项目结构(也在github 中):

??? build    <-- JS from compiled TS go here
??? node_modules
??? package.json
??? src
??? @types  <-- d.ts files 
??? test
??? tsconfig.json
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
  "compilerOptions": {
    "target": "es2017",
    "lib": ["esnext"],
    "module": "commonjs",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "outDir": "./build",

    "typeRoots" : ["./@types", "node_modules/@types"]
  },
  "exclude": ["**/node_modules"],
  "include": [
    "src",
    "test",
    "@types"
  ]
}
Run Code Online (Sandbox Code Playgroud)

更新

我确认问题与 相关ts-node,而不是与mocha. 跑步:

yarn ts-node src/client.ts
Run Code Online (Sandbox Code Playgroud)

返回相同的错误。

参考:

小智 14

您可以将以下配置添加到tsconfig.json文件中。

  "ts-node": {
    "files": true
  },
Run Code Online (Sandbox Code Playgroud)

它在我这边效果很好。

  • 我得到“未知的编译器选项‘ts-node’”。 (4认同)
  • `ts-node` 节点不能位于 `compiler-options` 内,它必须位于 `ts-config.json` 的根目录下。 (3认同)