gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:33:32 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com