2017-11-18 80 views
1

我有一個位於/src文件夾之外的NgModule Angular CLI項目(最終這個NgModule將打包爲npm模塊,但現在我只是把它留在/src之外)。Angular CLI - 如何在src文件夾外拾取.spec.ts文件?

我正在嘗試爲此NgModule編寫單元測試,但ng test似乎沒有在/src文件夾之外拾取.spec.ts文件。

我曾試圖改變在/src/test.ts路徑:

// Original 
const context = require.context('./', true, /\.spec\.ts$/); 

// Does not work 
const context = require.context('../', true, /\.spec\.ts$/); 

// Does not work 
const context = require.context('/absolute/path/to/ngmodule', true, /\.spec\.ts$/); 

但我得到一個錯誤:Module build failed: Error: /absolute/path/to/file.spec.ts is not part of the compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.

我自己也嘗試在tsconfig.spec.jsoninclude屬性添加路徑到我的NgModule:

"include": [ 
    "../my-ng-module/**/*.spec.ts", // Added this 
    "**/*.spec.ts", 
    "**/*.d.ts" 
] 

但沒有成功。有任何想法嗎?

回答

2

In tsconfig.spec.json

"include": [ 
    "../*.spec.ts", // your spec file location parent of src or ../yourpath/ 
    "**/*.spec.ts", 
    "**/*.d.ts" 
    ] 

In test.ts

if you pick parent dir it picks the other specs as well, hence when picking the parent dir of src then give your component name or specify the exact path of your spec

const context1 = require.context('./', true, /\.spec\.ts$/);// 
const context = require.context('../', true, /app\.component\.spec\.ts$/);// 
context.keys().map(context); 
context1.keys().map(context1); 

當你在SRC同樣的情況下正在加快其在node_modules文件的父文件夾,因此,我們需要提及spec.ts名。

spec.ts文件,這是SRC將運行像以前一樣 enter image description here

應用規範是在src和比賽規格的父母在爲src文件夾

If you want to specify only the root directory and from there you want to pick all the spec files then we give a different naming convention which differs from the spec files in node_modules. Say which are out of src as yourapp.componentout.spec.ts and which are inside insideapp.componentin.spec.ts and you can give one path instead of two directories

const context = require.context('../', true, /out\.spec\.ts$|in\.spec\.ts$/);// 
context.keys().map(context); 

或其他方式遵循命名約定爲僅在src之外的文件,並且將

const context1 = require.context('./', true, /\.spec\.ts$/);// 
const context = require.context('../', true, /out\.spec\.ts$/);// 
context.keys().map(context); 
context1.keys().map(context1); 

如果您不想更改規格文件名稱,則給出您的模塊位置的路徑,而不是其父節點,您可以跳過node_modules部分。

基本上,我們可以根據我們的需要

require.context(directory, useSubdirectories = false, regExp = /^\.\//) 

希望這有助於改變之下!

參考:https://webpack.js.org/guides/dependency-management/#require-context

+0

很好的答案!我永遠不會想到'tests.ts'中的附加上下文,我沒有看到任何文檔。非常感謝發佈 – Ryan

相關問題