Recently joining a new team that works with Angular, they asked me to implement unit testing on an existing project built with Angular 8. After researching the best approach, I decided to use Karma + Jasmine for testing. I set up a .spect.ts
file structured like this:
describe("CashFlowSalariesComponent", () => {
let fixture: ComponentFixture < CashFlowSalariesComponent > ;
let instance;
let profile: ProfileModel;
beforeEach(async() => {
TestBed.configureTestingModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA],
imports: [
// list of all imported modules
],
declarations: [CashFlowSalariesComponent],
providers: [
// long list of provided services
],
}).compileComponents();
fixture = TestBed.createComponent(CashFlowSalariesComponent);
instance = fixture.componentInstance;
fixture.detectChanges();
profile = new ProfileModel();
(instance as any).exchangeRate = 18.92;
});
afterEach(() => {
fixture.destroy();
});
it("To test instance creation of component", () => {
expect(instance).toBeTruthy();
});
Importing several services from providers was necessary due to their dependencies in my ApiService. Omitting these services resulted in errors like:
NullInjectorError: No provider for {serviceName}!
This led to developers having to manually copy and paste service imports from one component to another each time ApiService was used. Is there a more efficient way to handle these dependencies, such as creating a class to import all providers at once? How can this be accomplished?