Lesson 14

Testing Asynchronous Code

Using fakeAsync to control time and test asynchronous code

PRO

Lesson Outline

Testing Asynchronous Code

We're getting into some more complicated situations now, so before we continue with developing the application we are going to spend the next couple of lessons covering a couple more testing concepts.

Up until this point our tests have been reasonably simple, we have just been dealing with calling functions and passing data between pages. All the code we have been testing so far we have been able to test synchronously. Technically, we have already dealt with some asynchronous code as we have been dealing with observable streams, but the subscribeSpyTo method has been taking care of that for us and allowing us to test in a more synchronous manner.

The observer spy library is so awesome it feels like cheating, but in this lesson we are going to focus on the tools that Angular provides to us to help test asynchronous code (because even with the observer spy library, we will still sometimes need to utilise these additional methods - especially if you aren't building a "reactive" application with observable streams and no manual subscribes).

It gets a little more complicated when we start testing asynchronous code. Unlike synchronous code that gets executed right away, asynchronous code will get executed at some time after all the rest of our synchronous code has run. If we wanted to write a test that relied on the result of an asynchronous function like the following test:

it('someThing should be true after someAsynchronousFunction runs', () => {
  component.someAsynchronousFunction();

  expect(component.someThing).toBe(true);
});

Assuming that someAsynchronousFunction sets someThing to true after some asynchronous operation like resolving a promise, we are going to have issues when running this test.

The flow of our test would look something like this:

  1. Call someAsynchronousFunction
  2. Check that someThing is true
  3. Waiting for promise to resolve...
  4. someThing is set to true

Clearly, this is not what we want. We need someThing to be set to true before we check it with our expect statement. What we really want is this:

  1. Call someAsynchronousFunction
  2. Waiting for promise to resolve...
  3. someThing is set to true
  4. Check that someThing is true

In order to deal with this situation, we can run the test inside of fakeAsync which essentially gives us the ability to control time in our tests.

PRO

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).