Search⌘ K

Test Promises Using Async and Await

Learn to test Promises using async and await.

In everyday work, we often need to deal with Promises (MDN article). Jasmine allows for a straightforward way of testing these using async and await (MDN article)

The ArticleDelete class

What follows is a very simplified example of a class that handles deleting articles in a browser application. It accepts some input and makes a request to a server API if conditions are met.

For this lesson, the ArticleAPI methods are considered returning instances of Promise. So, the delete method returns a Promise.

Run the code playground below and see the breakdown below.

const specReporter = require('jasmine-spec-reporter').SpecReporter

module.exports = {
  srcDir: "src",
  srcFiles: [
    "**/*.?(m)js"
  ],
  specDir: "spec",
  specFiles: [
    "**/*[sS]pec.?(m)js"
  ],
  helpers: [
    "helpers/**/*.?(m)js"
  ],
  random: false,
  stopSpecOnExpectationFailure: false,
  browser: {
    name: "headlessChrome"
  },
  reporters: [new specReporter()]
}
Unit testing a Promise example

ArticleDelete class breakdown

The ArticleDelete class is relying on the ArticleAPI class to make a DELETE /api/article/:id call if conditions are met.

  • ArticleAPI is a class that would implement the server API call. It’s empty above because that’s outside of the current lesson scope, and we’ll be mocking its responses for the tests.

  • ArticleDelete is the main class. Its breakdown is below:

    • import { ArticleAPI } from './article-api.mjs';
      

      This line imports the ArticleAPI dependency from the adjacent module in the current folder, article-api.mjs.

    • export class ArticleDelete {
      

      This line declares and exports the class to be used in other modules.

    •   /** @type {ArticleAPI} */
        articleAPI;
      
        /**
         * @param { ArticleAPI } article the article api
         */
        constructor(articleApi) {
          this.articleAPI = articleApi;
        }
      

      These lines declare the articleAPI property and populates it when an instance of the class gets constructed. In other ...