...

/

Test Asynchronous Node.js API Logic using ExpectAsync

Test Asynchronous Node.js API Logic using ExpectAsync

Learn to test an implementation of an ArticleApiController with asynchronous get and delete endpoints on the server side.

One way of handling the API calls to the back-end is in a class dedicated to a resource, and we’ll look at one such implementation. The ArticleApiController implements a get method that returns the corresponding article by id. It also implements a delete method that deletes the article, given its id and etag.

Explore the following code playground, and let’s break it down after.

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

jasmine.getEnv().clearReporters();

jasmine.getEnv().addReporter(
  new SpecReporter({
    // add jasmine-spec-reporter
    spec: {
      displayPending: true,
    },
  })
)
Testing async Node.js API code

‘ArticleApiController’ class breakdown

If we use a web framework like express.js, it handles a lot of the HTTP stuff for us. We only need to implement our logic. The ArticleApiController is this logic. It exposes the method get that allows clients to request an article by providing an id. Looking at src/article-controller.js, we see the following :

  • db;
    
    constructor(db) {
      this.db = db;
    }
    

    The ArticleApiController expects to get a db, which would allow connecting and manipulating a database of some sort. This db is a dependency. We’ll mock it for the test, so we won’t get into further details here. For the example, we assume it to be a mongodb connection. ...

  • async get(id) {
      try {
        const a = await this.db.collection('Article').findOne({ id: id });
        return a;
      } catch (e) {
        throw { status: 'not found', message: