NodeJS 如何在mocha测试中从使用require语句切换到使用typescript导入?

7eumitmz  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(122)

我在package.json中有以下值:

"scripts": {
        "test": "mocha -r ts-node/register security.test.ts"
    },
     "type": "module", 
      .
      .
      .

我的tsconfig.json文件:

{
      "compilerOptions": {
        "esModuleInterop": true,
        "module": "ESNext",
        "target": "ESNext",
        "resolveJsonModule": true,
        "moduleResolution": "Node"
      },
      "ts-node": {
        "esm": true,
        "experimentalSpecifierResolution": "node"
      },
      "include": [
            "*.ts",
            "**/*.ts",
            "**/*.test.ts"
    ]
  }

在security.test.ts文件中,我有

import { describe, it, before, after } from "mocha";

  describe("Testing for project", async () => {
 
      before(async () => {
        console.log("before");
      });
    
      after(async () => {
        console.log("ran after");
      });

我尝试的每个配置都会得到这个错误,除非我将其切换回require语句:
mocha-r ts-node/register security.test.ts

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /myfilepath.ts
at new NodeError (node:internal/errors:399:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:79:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:121:38)
    at defaultLoad (node:internal/modules/esm/load:81:20)
    at nextLoad (node:internal/modules/esm/loader:163:28)
    at ESMLoader.load (node:internal/modules/esm/loader:605:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:457:22)
    at new ModuleJob (node:internal/modules/esm/module_job:64:26)
    at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:480:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:434:34)

我错过了什么?换衣服有这么痛苦吗?

r1zhe5dt

r1zhe5dt1#

tsconfig文件

{
  "compilerOptions": {
    "esModuleInterop": true,
    "module": "ESNext",
    "target": "ESNext",
    "resolveJsonModule": true,
    "moduleResolution": "Node"
  },
  "include": [
    "*.ts",
    "**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

package.json

"scripts": {
    "test": "mocha --require ts-node/register security.test.ts",
    "start": "node -r ts-node/register your-script.ts"
  },
  "type": "module"
}

运行npm install ts-node mocha @types/mocha --save-dev,确保安装了必要的依赖项
security.test.ts

describe("Testing for project", async () => {
  before(async () => {
    console.log("before");
  });

  after(async () => {
    console.log("ran after");
  });

  it("should run a test", async () => {
    // Add your test logic here
  });
});

在更改此文件后,然后启动npm测试

相关问题