与全局供应商进行 Angular 2 测试

标签 angular karma-runner angular-cli

我正在 angular cli 项目中测试很多组件,我在其中一些组件中使用 RouterTestingModule 来对路由器进行 stub 。我只想将 RouterTestingModule 添加到所有测试中,这样我就不必有选择地添加它。

我将它添加到 test.js 中的测试设置中,如下所示,但它似乎并未包含在组件的测试模块中。这是包含“全局”提供商的正确方法吗?

Promise.all([
    System.import('@angular/core/testing'),
    System.import('@angular/platform-browser-dynamic/testing'),
    System.import('@angular/router/testing'),
])
    // First, initialize the Angular testing environment.
    .then(([testing, testingBrowser, testingRouter]) => {
        testing.getTestBed().initTestEnvironment(
            testingBrowser.BrowserDynamicTestingModule,
            testingBrowser.platformBrowserDynamicTesting(),
            testingRouter.RouterTestingModule,
        );
    })
    // Then we find all the tests.
    .then(() => require.context('./', true, /\.spec\.ts/))
    // And load the modules.
    .then(context => context.keys().map(context))
    // Finally, start Karma to run the tests.
    .then(__karma__.start, __karma__.error);

关于 initTestEnvironment 的文档是这样说的:

This may only be called once, to set up the common providers for the current test suite on the current platform.

最佳答案

有点晚了,但解决方案是将一组提供程序传递给 platformBrowserDynamicTesting() 函数。

Promise.all([
    System.import('@angular/core/testing'),
    System.import('@angular/platform-browser-dynamic/testing'),
    System.import('@angular/router/testing'),
])
    // First, initialize the Angular testing environment.
    .then(([testing, testingBrowser, testingRouter]) => {
        testing.getTestBed().initTestEnvironment(
            testingBrowser.BrowserDynamicTestingModule,
            testingBrowser.platformBrowserDynamicTesting([..<providers here>..])
        );
    })
    // Then we find all the tests.
    .then(() => require.context('./', true, /\.spec\.ts/))
    // And load the modules.
    .then(context => context.keys().map(context))
    // Finally, start Karma to run the tests.
    .then(__karma__.start, __karma__.error);

关于与全局供应商进行 Angular 2 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40911513/

相关文章:

javascript - Angular 8 : Create Facade Pattern for Subject-Observable design, 发布/订阅

Angular 4 : Close modal after form submit event is finished

css - Ionic 5 在 iOS 上设置可折叠标题颜色

angularjs - e2e 测试和 $timeout

angularjs - 将 angular-seed jasmine 单元测试转换为 coffeescript

TypeScript 编译失败和 Karma 测试执行?

javascript - Angular 编译器 "compile"是什么?

angular-cli - 使用 Angular-CLI 构建复制文件/目录

带有 Lazy-Loaded 路由的 Angular CLI HMR 热重载整个东西

twitter-bootstrap - 为单个 `ngFor` 迭代创建两个元素?