In continuation of the previous question (linked here), I am still working on tutorials for Angular testing using the same files. The current issue revolves around the setTimeout function.
Within both ngOnInit and ngAfterViewInit, I have included a setTimeout function (as future tests will also utilize this). The function sets a variable value that is then passed to a child component through the HTML file, and I need to check if the child component's variable has the expected value.
Despite trying to use tick(value) and fixture.detectChanges() to trigger the contents of the setTimeout function, the value remains undefined. Below are code snippets demonstrating the setup:
random.test.component.ts
public dataThatGetsDelayed: any;
constructor() {
}
ngOnInit() {
setTimeout(() => {
this.dataThatGetsDelayed = "OnInit";
}, 100);
}
ngAfterViewInit() {
setTimeout(() => {
this.dataThatGetsDelayed = "AfterView";
}, 100);
}
random.test.component.html
[variableThatStoresDelayedData]="dataThatGetsDelayed"
random.test.component.child.ts
@Input() variableThatStoresDelayedData: any;
random.test.file.spec.ts
it('Testing if receiving input works properly with a time delay in ngOnInit', fakeAsync(() => {
const componentInThePage: TestComponentChild = fixture.debugElement.query(By.directive(TestComponentChild)).componentInstance;
expect(componentInThePage).toBeTruthy();
tick(100);
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(componentInThePage.variableThatStoresDelayedData).toEqual("OnInit");
});
}));
it('Testing if receiving input works properly with a time delay in ngAfterViewInit', fakeAsync(() => {
const componentInThePage: TestComponentChild = fixture.debugElement.query(By.directive(TestComponentChild)).componentInstance;
expect(componentInThePage).toBeTruthy();
//tick(100);
//component.ngAfterViewInit();
fixture.whenStable().then(() => {
expect(componentInThePage.variableThatStoresDelayedData).toEqual("AfterView");
});
}));
I have attempted to use whenStable at the end as recommended, but it seems to be disregarded. Without it, I receive the error "Expected undefined to equal 'OnInit'/'AfterView'". I have avoided the second tick as it results in the error "1 timer(s) still in the queue".
How can I instruct the program to wait until the setTimeout function sets the variable value?