2017-05-01 17 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)