运行 测试位于与 mocha 和 ts-node 不同的目录中?

Running tests located in a separate directory with mocha and ts-node?

我将源代码和测试分开如下:

`src/main/ts/hello.ts`  //SOURCE FILES HERE
`src/test/ts/hello.spec.ts` //SPEC FILES HERE

src/test/ts/hello.spec.ts 中的导入语句如下所示:

import hello from 'hello';

hello.ts 源代码如下所示:

    export function hello() {
      return 'Hello World!';
    }

    export default hello;

我的 tsconfig.json 设置为测试文件可以导入源模块而不使用像这样的相对路径:

    {
       "include": [
         "src/main/ts/**/*.ts"
       ],
       "exclude": [
         "node_modules"
       ],

       "compilerOptions": {
         "experimentalDecorators": true,
         "noImplicitAny": true,
         "moduleResolution": "node",
         "target": "es6",
         "baseUrl": ".",
         "paths": {
           "*": [
             "*", "src/main/ts/*"
           ]
         }
       }
     }

这样 hello.spec.ts 文件可以使用语句 import hello from 'hello';

导入 hello

我正在尝试 运行 测试 npm test 配置为 运行 mocha 和 tsnode 像这样(基于 this article):

"scripts": {
  "test": "mocha -r ts-node/register src/test/ts"
},

然而,当我收到此错误时,ts-node 似乎没有接受我的 tsconfig.json 配置:

mocha -r ts-node/register src/test/ts

Error: Cannot find module 'hello'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:286:25)

您在 tsconfig.json 中通过 paths 设置的模块分辨率纯粹是 编译时的事情 。 (有关详细信息,请参阅此 ts-node issue report and this TypeScript issue report。)它不会影响代码的发出方式,这意味着您的测试文件正在执行 require("hello"),Node 无法解析。 paths 是编译时的结果是你的模块加载器需要配置为 执行你在 tsconfig.json 中指定的相同类型的解析.例如,如果您使用的是 RequireJS,则需要为其配置一个与 pathstsconfig.json 中执行相同操作的配置。您正在使用 Node,但是...

您在 Node 中可以做的是使用 tsconfig-paths,它将读取 tsconfig.json,解析 paths 设置并更改 Node 中的模块分辨率以使其工作。

使用您的代码,我修改了 hello.spec.ts 以进行至少一项反馈测试:

import hello from "hello";
import "mocha";

it("q", () => {
    if (hello() !== "Hello World!") {
        throw new Error("unequal");
    }
});

我安装了 tsconfig-paths@types/mocha(以便 import "mocha" 在上面显示的测试文件中进行正确的编译)并像这样调用 Mocha:

$ ./node_modules/.bin/mocha --compilers ts:ts-node/register -r tsconfig-paths/register 'src/test/ts/**/*.ts'

我得到了这个输出:

  ✓ q

  1 passing (20ms)