Han Che
Han Che

Reputation: 8519

angular 4+ - import modules globally for testing

I'm just getting started writting unit tests for angular. As I am using ngx-translate in literally every component (and some services) I wanted to ask if there was a way to import and provide it on a global testing level.

So far I have provided and imported the ngx-translate module and http-loader in each .spec file like this

export function createTranslateLoader(http: HttpClient) {
    return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

describe('AppComponent', () => {
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [
                HttpClientModule,
                TranslateModule.forRoot({
                    loader: {
                        provide: TranslateLoader,
                        useFactory: (createTranslateLoader),
                        deps: [HttpClient]
                    }
                }),
            ],
            declarations: [
                AppComponent
            ]
        }).compileComponents();
    }));
}

Upvotes: 4

Views: 2919

Answers (2)

Nicolas Gehlert
Nicolas Gehlert

Reputation: 3253

you can do this in your global test.js setup file were you call initTestEnvironment.

You can add a custom module there, something similar to

@NgModule({
    imports: [
      YourTestingModule,
    ],
    providers: [
        {provide: YOUR_TOKEN, useValue: 'yourValue'},
    ],
})
class GlobalTestingSetupModule {}

TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(
    [
        BrowserDynamicTestingModule,
        GlobalTestingSetupModule,
    ],
    platformBrowserDynamicTesting(),
    {},
);

example taken from: https://developapa.com/angular-jest-karma-config/

Upvotes: 1

anteAdamovic
anteAdamovic

Reputation: 1468

You could provide it on the global testing level although it's intended to be imported and provided per module as that's in the spirit of Unit Testing.

Depending on your configuration you should have a configuration-test.module.ts where you bootstrap your TestBed with the appInjector, if you provide services in that module they will be provided for all describe() tests but you will still need to inject them manually in your components.

Upvotes: 1

Related Questions