简体   繁体   English

与全球提供商进行Angular 2测试

[英]Angular 2 testing with global providers

I am testing a lot of components in an angular cli project, and I'm using RouterTestingModule in some of them to stub the router. 我正在测试一个角度cli项目中的很多组件,我在其中一些中使用RouterTestingModule来存根路由器。 I'd like to just add RouterTestingModule to all tests so I don't have to selectively add it. 我想将RouterTestingModule添加到所有测试中,所以我不必有选择地添加它。

I added it to the test setup in test.js like below, but it does not seem to be included in the test modules for the components. 我将它添加到test.js的测试设置中,如下所示,但它似乎没有包含在组件的测试模块中。 Is this the correct way to include "global" providers? 这是包含“全球”提供商的正确方法吗?

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);

The docs say this about initTestEnvironment : 关于initTestEnvironment的文档说这个:

This may only be called once, to set up the common providers for the current test suite on the current platform. 这可能只被调用一次,以便为当前平台上的当前测试套件设置公共提供程序。

A little late but solution is to pass an array of providers to platformBrowserDynamicTesting() function. 稍晚但解决方案是将一组提供程序传递给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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM