Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 5 testing - configure testbed globally

I want to import certain modules for all testing suits such as ngrx Store, ngx translate or httpClientModule in an [email protected] project with angular 5.

in the generated test.ts I have added a test.configureTestingModule

const testBed: TestBed = getTestBed();

testBed.initTestEnvironment(
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting()
);

testBed.configureTestingModule({
    imports: [
        HttpClientModule,
        StoreModule.forRoot(reducers, { metaReducers }),
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: (createTranslateLoader),
                deps: [HttpClient]
            }
        }),
    ]
}

Still in a user.servive.spec.ts it says no provider for Store.

user.service.spec.ts

describe('UserService', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [UserService]
        });
    });

    it('should be created', inject([UserService], (service: UserService) => {
        expect(service).toBeTruthy();
    }));
});

Does the Test.configureTestingModule in user.service.spec "overwrite" the one from test.ts?

If so, how can I configure the TestBed on a global level to avoid importing repetitive modules?

Thanks!

like image 234
Han Che Avatar asked Nov 09 '17 14:11

Han Che


1 Answers

The short answer is that TestBed hooks into Jasmine's beforeEach and afterEach callbacks which resets the testing module between EVERY test. This gives you a clean-slate for each unit test.

This means that you cannot use TestBed.configureTestingModule inside your test.ts file. You must do it for each spec manually or write your own default test setup utilities to handle it.

I'm the dev for shallow-render which does have a solution for this by using Shallow.alwaysProvide() to globally setup/override/mock providers and forRooted providers in your test environment. The rest of your test module setup is handled by the library.

https://github.com/getsaf/shallow-render#global-providers-with-alwaysprovide

Hope this helps.

like image 80
getsaf Avatar answered Sep 30 '22 01:09

getsaf