Home > OS >  Angular component testing: Asynchronous test fails without sleep #47006
Angular component testing: Asynchronous test fails without sleep #47006

Time:08-03

I have a component that allows images uploading, once the user adds an image, it emits an event (the parent should handle it), but doing some unit test over that component I'm not able to pass the test without doing some sleep (wait for event to be triggered).

Test purpose: Validate (spy) the event is emitted

spyOn(component.fileAdded, 'emit');
uploadFiles(element, [new File([''], 'test_file.png')]);
fixture.detectChanges();

expect(component.fileAdded.emit).toHaveBeenCalledWith({
  filePath: jasmine.any(String),
  fileBase64: jasmine.any(String),
});

See reproduction

I tested:

  • With waitForAsync async fn -> FAIL
  • With waitForAsync await whenStabale fn -> FAIL
  • With fakeAsync tick -> FAIL
  • With fakeAsync flush -> FAIL
  • With fakeAsync flushMicrotasks -> FAIL
  • With fakeAsync whenStable -> FAIL
  • Native async with sleep -> PASS

I'm missing something or doing something wrong?

  • Related