Angular fakeAsync Gotcha with Mock Dependencies

tl;dr

  • A subsequent fakeAsync unit test fails due to a Typescript type error after a successful fakeAsync unit test.
  • Try putting the act and assert portions of the unit test into a fakeAsync block instead of wrapping the entire unit test in a fakeAsync block.

The Problem

A working unit test was failing due to a type error only on the second fakeAsync unit test. The second test failed even when I swapped the order of the tests.

My scenario:

  • Provided testBed services are injected in a beforeEach
  • Individual specs are wrapped in fakeAsync functions
  • The service under test calls a function of an object created by a mocked dependency.

No matter which order you put the specs, the second one will fail due to a type error of respond method not found on the dependencyObject.

A similar issue was pointed out in this issue thread and is described in the Angular changelog: “ The injection instance will be that of MockFoo but the type will be Foo instead of any as in the past. This means that it was possible to call a method on MockFoo in the past which now will fail type check.”

Though this does not explain why it works the first time but not the second.

The Solution

Only put the act and assert portions of your test in a fakeAsync block. NOT the entire spec as demonstrated in the documentation (and in pretty much every article on fakeAsync).

I blew a morning on this so hopefully this helps someone out there.