2017-05-01 16 views
0

我已经源代码和检验分离如下:运行测试位于一个单独的目录与摩卡和TS节点?

`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设置为使得测试文件可以导入源模块而不使用相对pa部份是这样的:

{ 
     "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';

我试图用npm test配置为运行摩卡和tsnode像这样运行测试的语句来导入hello(基于this article) :

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

但是它看起来并不像TS-节点拿起我的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) 

回答

1

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

您可以在节点中执行的操作是使用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"做正确的事汇编明智的测试文件我看到前面),并调用摩卡这样的:

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

我得到这样的输出:

✓ q 

    1 passing (20ms)