【问题标题】:Angular 2 testing with global providersAngular 2 与全球供应商的测试
【发布时间】:2016-12-01 13:10:01
【问题描述】:

我正在一个 Angular cli 项目中测试很多组件,我在其中一些组件中使用RouterTestingModule 来存根路由器。我只想将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 这么说:

这只能被调用一次,以便为 当前平台上的当前测试套件。

【问题讨论】:

    标签: angular karma-runner angular-cli


    【解决方案1】:

    有点晚了,但解决方案是将一组提供者传递给 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);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-19
      • 2018-01-16
      • 2017-07-25
      • 2016-09-16
      • 2016-10-24
      • 2020-08-14
      • 1970-01-01
      • 2020-11-27
      相关资源
      最近更新 更多