Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

like image 593
altschuler Avatar asked Apr 12 '26 19:04

altschuler


1 Answers

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);
like image 91
Yildiray Meric Avatar answered Apr 14 '26 12:04

Yildiray Meric