我正在 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/