【问题标题】:Running tests located in a separate directory with mocha and ts-node?使用 mocha 和 ts-node 运行位于单独目录中的测试?
【发布时间】:2017-09-28 22:49:03
【问题描述】:

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

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

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

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)

【问题讨论】:

    标签: node.js typescript mocha.js typescript2.0 ts-node


    【解决方案1】:

    您在tsconfig.json 中通过paths 设置的模块分辨率纯粹是编译时的事情。 (有关详细信息,请参阅此 ts-node issue report 和此 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多