I have written the following code with async unit testing but these are failing randomly not consistently. Can anyone help me what here wrong?
The test case is: When the user pressed keyboard keys W (go to the previous doc) and S(go to next doc) then on UI selected document(row) should be changed in table.
it('When user press key W and S then should be able navigate to previous and next document', async () => {
createTestBed();
fixture.detectChanges();
const searchResultStub = MockNgRedux.getSelectorStub(['documentSearch', 'results']);
searchResultStub.next(getSearchResult());
searchResultStub.complete();
fixture.detectChanges();
const spyPrevElement = spyOn(comp.documentSearchResult._tableService, 'selectPrevElement').and.callThrough();
const spysNextElement = spyOn(comp.documentSearchResult._tableService, 'selectNextElement').and.callThrough();
await TestUtil.SleepForASecond(0);
document.dispatchEvent(TestUtil.createKeyUpEvent("S"));
fixture.detectChanges();
expect(spysNextElement).toHaveBeenCalled();
expect(spysNextElement).toHaveBeenCalledTimes(1);
document.dispatchEvent(TestUtil.createKeyUpEvent("W"));
fixture.detectChanges();
expect(spyPrevElement).toHaveBeenCalled();
expect(spyPrevElement).toHaveBeenCalledTimes(1);
});
TestUtil.ts file:
static async SleepForASecond(ms) {
await new Promise(resolve => setTimeout(resolve, ms);
}
static createKeyUpEvent(key: string, isCapsOn: boolean = false) {
const keyUpEvent: Event = new KeyboardEvent('keyup', {
'key': key,
'modifierCapsLock': isCapsOn
});
return keyUpEvent;
}
Similar for this other tests are failing due to async and await with the following error. Can anyone have an idea?
Error: Timeout - Async callback was not invoked with 5000ms(set by jasmine.DEFAULT_TIMEOUT_INTERVAL) at <Jasmine>
OBSERVATION: TEST CASES ARE MORE FAILING INSIDE DOCKER CONTAINER. TESTS WOULD SOMETIMES PASS WITHOUT ANY ISSUES BUT SOMETIMES FAIL.