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. I'd like to just add RouterTestingModule to all tests so I don't have to selectively add it.
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. 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:
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With