Search code examples
angularkarma-jasmineangular-unit-testkarma-jasmine-ajax

Angular8 unit testing jasmine timeout issue


Running into random unit test failures with this failure mode

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

Some of these tests that failed do not even have async testing going on!

Wondering if this snippet of code is correct or not; it is a pattern we use across the board in all tests in Angular

beforeEach(async(() => {
    TestBed.configureTestingModule({ . // Should this be **return TestBed.configureTestingModule**
      imports: [
        ...CommonTestModules
      ],
      declarations: [FooComponent]
    })
    .compileComponents();
  }));

Should the promise of compileComponents be returned from the callback? I read somewhere that the promises are awaited for by the async wrapper which eventually calls done() when the promises are resolved. But here this pattern looks like it is not returning the promise and we are not invoking the "await" keyword anywhere either. Does this code appear wrong without the return statement?


Solution

  • It's ok to not return that promise, the async function takes care of waiting for all promises created inside of the beforeEach. You can see that pattern throughout the Angular Testing docs:

    beforeEach(async(() => {
      TestBed.configureTestingModule({
        declarations: [ BannerComponent ],
      })
      .compileComponents();  // compile template and css
    }));
    

    It's possible your IDE will complain, like WebStorm does, because it doesn't know the semantics of Angular's async function (notice this is not the same async keyword from JavaScript, this one is a function declared in Angular

    About your original error, try to isolate a test that fails, or add an example of one of those tests that sometimes fail to see if we see anything weird.