在require.context()中使用模块路径时,afterAll [object ErrorEvent]中引发了错误

时间:2019-07-23 08:11:39

标签: angular unit-testing angular-cli karma-jasmine

当我使用以下配置执行ng test时,我的Angular应用程序中遇到一个非常奇怪的错误:

const context: any = require.context('./', true, /\.spec\.ts$/); // all modules
const contextModule1: any = require.context('./app/modules/abc-module', true, /\.spec\.ts$/); // ABC module only
const contextModule2: any = require.context('./app/modules/def-module', true, /\.spec\.ts$/); // DEF module only

运行所有(300+)个测试均成功:

context.keys().map(context); // path: './'

但是仅在其中一个模块中运行测试会失败:

context.keys().map(contextModule1); // path: './app/modules/abc-module'

(正确的)两个路径均失败:

  

afterAll [object ErrorEvent]中引发了一个错误

这似乎完全无关。关于可能是什么原因的任何想法?

1 个答案:

答案 0 :(得分:0)

将test.ts配置更改为此即可解决:

// const context: any = require.context('./', true, /\.spec\.ts$/);
// const context: any = require.context('./app/modules/abc-module', true, /\.spec\.ts$/);
const context: any = require.context('./app/modules/def-module', true, /\.spec\.ts$/);

context.keys().map(context);

它必须是相同的变量:context。更改map()中的变量似乎会导致错误。相反,我必须使用注释才能在三个路径之间切换。

我知道,require.context的参数必须是静态的而不是变量,但是将多个require.context()保存在不同的变量中不应与此相矛盾-因此,我没有该错误的解释。