angular 5 testing - configure testbed globally

Viewed 4401

I want to import certain modules for all testing suits such as ngrx Store, ngx translate or httpClientModule in an angular-cli@1.50 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!

3 Answers

The other answer covers the way configureTestingModule works before/after individual tests, but you don't necessarily have to use a plugin to have a simple "always provide" module setup. I created a paths alias in my testing tsconfig:

        "paths": {
            "@testing": ["src/testing/index"],
            "@testing/*": ["src/testing/*"]
        }

This lets me write a TestModule module with all the shared imports:

@NgModule({
  imports: [
    // All repeated modules
  ],
})
export class TestModule { }

Then, each call to configureTestingModule only needs to import { TestCommon } "@testing/test-common.module" and include it in the imports section of the test module config.

There is no need to go for a separate library just to achieve this. You can create a global TestBed just by creating a common angular module where you can define a utility method. This utility method creates the TestBed which you can then reuse across all your spec files.

You can refer to the answer below which also includes sample code: https://stackoverflow.com/a/64835814/4184651

Related