Reputation: 561
We have a legacy Angular 4 project using SystemJS. We have been asked to implement unit test cases using Jasmine and Karma. I started writing a test suite for one component. It looks something like this (pseudo code below):
beforeEach(async(() => {
TestBed.configureTestingModule(
imports,
providers,
declarations etc.
).compileComponents();
}));
We have a lot of initialization code in an APP_INITIALIZER, that sets up various pieces of state in the application (such as Reference data, configuration, user information). For the test cases to run smoothly, we need the Initialization code to run. Any idea how this can be achieved?
Upvotes: 1
Views: 2198
Reputation: 517
If you're trying to actually run your App Initializer, modify your test's beforeEach
method to setup the testbed to make it similar to your NgModule:
TestBed.configureTestingModule({
declarations: [],
providers: [
{
provide: APP_INITIALIZER,
useFactory: <factory function here>,
multi: true,
deps: [
<any dependencies of your initializer here>
]
}
],
imports: [
<if you use HTTP, add 'HttpClientMOdule' here>
]
});
Note that many will recommend using a mock or spy instead of the actual factory that you use in production. That choice is up to you and depends on your specific needs.
After you call configureTestingModule
, you will also need to do this (see https://github.com/angular/angular/issues/24218) and mark your beforeEach as async
:
await TestBed.inject(ApplicationInitStatus).donePromise;
Hope this helps!
Upvotes: 1