Han Che
Han Che

Reputation: 8519

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!

Upvotes: 9

Views: 6189

Answers (4)

Leaky
Leaky

Reputation: 3636

Old question, but I still ended up here in 2024 while looking for solutions for global testbed configuration.

I desperately needed to mock a root service globally, and I wanted to find a solution that didn't require touching all spec.ts files (like with e.g. referencing a base test config).

After hours of search I realized that you can apply a global configuration embarassingly easily in the test.ts file (for example) by simply calling Jasmine's global beforeEach() method, and inside that calling TestBed functions:

beforeEach(() => 
  // Or other configuration functions
  TestBed.overrideProvider(ServiceOrComponentName, { useValue: MockName })
);

To further clarify, this is how an example test.ts could look like with the simple global configuration addition:

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);

beforeEach(() => 
  // Or other configuration functions
  TestBed.overrideProvider(ServiceOrComponentName, { useValue: MockName })
);

I'm not an expert in frontend unit testing, but this solution so far proved to be working in a robust manner in our project without any side effects.

Upvotes: 0

Evan MJ
Evan MJ

Reputation: 2813

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

Upvotes: 0

Coderer
Coderer

Reputation: 27244

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.

Upvotes: 1

getsaf
getsaf

Reputation: 1761

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.

Upvotes: 4

Related Questions