7

我有一个 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$/);

但我收到一个错误: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.

我还尝试在以下include属性中添加我的 NgModule 的路径tsconfig.spec.json

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

但没有成功。有任何想法吗?

4

2 回答 2

11

在 tsconfig.spec.json

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

在 test.ts

如果您选择父目录,它也会选择其他规范,因此在选择 src 的父目录时,请给出您的组件名称或指定您的规范的确切路径

 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 文件将像以前一样运行 在此处输入图像描述

应用规范在 src 的父级中,游戏规范在 src 文件夹中

如果您只想指定根目录并从那里选择所有规范文件,那么我们会给出与 node_modules 中的规范文件不同的命名约定。说哪些在 src 之外作为 yourapp.componentout.spec.ts 哪些在 insideapp.componentin.spec.ts 中,你可以给出一个路径而不是两个目录

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

于 2017-11-18T16:40:33.807 回答
0

以下命令将有所帮助

ng test --include='src/app/modulefolder/**/*.spec.ts'
于 2021-06-29T04:46:24.670 回答