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

How to use TypeScript Declaration File with mocha tests?

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

% 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";

似乎 ts-node 无法识别 d.ts 个文件。

唯一可行的解​​决方案是使用 require 而不是 import 语句,但这不会 link algosdk 的类型。

如何在 TS 文件和类型定义文件中使用 mocha?

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

├── build    <-- JS from compiled TS go here
├── node_modules
├── package.json
├── src
├── @types  <-- d.ts files 
├── test
├── tsconfig.json

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"
  ]
}

更新

我确认问题与 ts-node 有关,与 mocha 无关。 运行:

yarn ts-node src/client.ts

returns同样的错误。

参考文献:

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

  "ts-node": {
    "files": true
  },

我这边效果很好。