angular 5 testing - configure testbed globally
Asked Answered
C

4

8

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!

Callow answered 9/11, 2017 at 14:30 Comment(4)
I don't have your userService, but I'm pretty sure the error is because you forgot to import the Store service in your testbed. What is the constructor of your userService ?Vermination
i didn't forget, i want to import and provide the store globally for all tests, that why i've imported it in test.tsCallow
Tests are made in one file and are not global (for all I know). If you want to 'make it global', you will have to make an utils file that is able to construct a testbed, then call it in a beforeEach in every file.Vermination
thats what some other blogs have hinted, but thanks for the clarification!Callow
I
4

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.

Involution answered 5/4, 2018 at 21:50 Comment(0)
B
1

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.

Backstroke answered 7/10, 2020 at 11:33 Comment(0)
C
0

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://mcmap.net/q/1012215/-how-to-reuse-all-imports-in-angular-test-files

Clippard answered 14/11, 2020 at 16:1 Comment(0)
W
0

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.

Wnw answered 25/1 at 17:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.