Lesson 14

Testing Asynchronous Code

WARNING: This module is deprecated and no longer receives updates. Protractor is likely being removed as the default from Angular applications and Protractor itself will likely stop receiving updates and development in the future. I would recommend checking out the Test Driven Development with Cypress/Jest as a replacement.

Using fakeAsync to control time and test asynchronous code


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 has been synchronous, which means everything has been getting executed one line after the other and we can just trigger whatever function we are interested in, and then test that something happened.

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', () => {


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.

fakeAsync, flushMicrotasks, and tick


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).