Context
My issue is that my ngOnInit function calls many sub functions asynchronously by using Firestore to populate a form from one document as well as subscribing to various collections to display lists of data. This gets very tedious to test as I then have to ensure things are subscribing properly and values are being returned in the correct order.
According to the Angular docs:
However, it's often more productive to explore the inner logic of application classes with isolated unit tests that don't depend upon Angular. Such tests are often smaller and easier to read, write, and maintain.
Which in my opinion would make preventing the ngOnInit (through a spy) a valid way of
Isolating tests and
Reducing complexity when initializing the tests
You can then explicitly call each function separately and only test what is needed, instead of having ngOnInit calling the functions (and possible you as well).
This is exactly how I have gone about it so far:
Component
ngOnInit() {
console.log('init');
this.setup();
}
setup() {
this.firebaseService.setup(_ => {
this.checkNewOrEdit();
});
}
...
Spec
...
beforeEach(() => {
fixture = TestBed.createComponent(Component);
component = fixture.componentInstance;
spyOn(component, 'ngOnInit');
fixture.detectChanges();
});
it('should be created', () => {
fixture.whenStable().then(_ => {
expect(component).toBeTruthy();
});
});
it('should call checkNewOrEdit() on setup()',
() => {
spyOn(component, 'checkNewOrEdit');
callbackValue = 'success';
component.setup();
expect(component.checkNewOrEdit).toHaveBeenCalled();
}
);
Which is working fine for me so far.
Is this an acceptable solution? Or are there better ways of going about this?