Angular CLI - 如何在 src 文件夹之外获取 .spec.ts 文件?

标签 angular angular-test

我有一个 Angular CLI 项目,其中一个 NgModule 位于 /src 文件夹之外(最终这个 NgModule 将被打包为一个 npm 模块,但现在我是将它留在 /src 之外)。

我正在尝试为这个 NgModule 编写单元测试,但是 ng test 似乎没有获取 /之外的 .spec.ts 文件src 文件夹。

我已经尝试改变 /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$/);

但我得到一个错误:模块构建失败:错误:/absolute/path/to/file.spec.ts 不是编译的一部分。请通过"file"或“包含”属性确保它在您的 tsconfig 中。

我还尝试在 tsconfig.spec.jsoninclude 属性中添加我的 NgModule 的路径:

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

但是没有成功。有什么想法吗?

最佳答案

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 名称。

src 中的 spec.ts 文件将像以前一样运行 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

关于Angular CLI - 如何在 src 文件夹之外获取 .spec.ts 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47364840/

相关文章:

Angular2——Angular-CLI——从自动构建观察者中排除文件夹

Mat-Menu 上 Angular-Material 的 Angular Testing

angular - 如何使用 Jasmine 对 Promise catch 进行单元测试

angular - 如何测试一个简单的 Angular Reactive Form

使用 Google 登录弹出窗口进行 Angular Cypress.io 测试

asp.net - Angular 2 无法使用 asp.net MVC 5 Web Api 调用自定义 Web Api

使用正则表达式的 HTML 时间输入验证(不允许 00 :00 but want allow 24:00)

javascript - 如何在传单中查找相邻的多边形

angular - 使用 UMD bundle bundle Angular 2 应用程序(不构建 vendor bundle )