Dany Paredes
Dany Paredes | Javascript / Web

Dany Paredes | Javascript / Web

How to test promises with Mocha.

How to test promises with Mocha.

Dany Paredes's photo
Dany Paredes
·Aug 12, 2020·

3 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

“The promises”, is a common task for javascript developers to run async code, but how I can test it ?.

Feel free to read the code on Github or continue reading.

I will write a method that returns a promise, and we will add a test for the resolved and rejected promise.

The Fake API

Create a file api.js with an array with a list of teams and export it.

module. exports = [
  {
    id: 1,
    team: "Raptors",
    player: "Kawhi Leonard",
    comment: "Raptors are the best east team",
  },
  {
    id: 2,
    team: "Lakers",
    player: "Lebron James",
    comment: "Lakers is out of playoffs",
  },
]

The code

Create a file named teams.js, import the API using require and create the function getTeamByPlayer it will return a promise, using setTimeout to simulate the async process.

We promise to return the resolve if the team with the player is found or the reject with an error if not found. Export the function to be used.

getTeamByPlayer is a simple function. It gets the player and finds into our array if it is found to return the resolve or return reject.

const teams = require("./api")
function getTeamByPlayer(player) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const filterTeams = teams.find((t) => t.player === player)
      filterTeams
        ? resolve({ message: "found", team: filterTeams })
        : reject(new Error("not found"))
    }, 1000)
  })
}
module.exports = { getTeamByPlayer }

The Test

Import assert like in the preview post, the getTeamByPlayer using require from the teams.js, and using the describe and it set up the test similar to my preview post.

.. But with just only difference, use async and await. We can do the same for testing if you are using async and await to handle your async code.

The declaration should be async to use the await until the promises are resolved or rejected, write a test for Find the player and another for getting the error not found.

const assert = require('assert')
const { getTeamByPlayer } = require('../src/teams');describe('Get teams from API', () => {
    it('Return the team by player', async () => {
        const actual = await getTeamByPlayer('Lebron James')
        const expect = {
            "message": "found",
            team: {
                id: 2,
                team: 'Lakers',
                player: 'Lebron James',
                comment: 'Lakers is out of playoffs'
            }
        }
        assert.deepEqual(actual, expect);
    }) it('Throw a error if player not found', async () => {
        const actual = await getTeamByPlayer('Irving').catch((error) => {
            assert.equal(error.message, 'not found')
        })
    })})

Run the test npm test and check the results.

danys-imac:demo danyparedes$ npm test\> demo@1.0.0 test /Users/danyparedes/Downloads/demo
> mocha
  IVA tax calculation
    ✓ calculate 15 of 1250
    ✓ calculate the total with 21 IVA
  Get teams from API
    ✓ Find team by team player (1003ms)
    ✓ Throw an error if the player not found (1004ms)
  Four passing (2s)

That’s it!

Hopefully, that will give you a bit of a head-start with async methods with Mocha and help you avoid some of the more common mistakes. If you enjoyed this post, share it.

Thanks for reading!

Photo by Mufid Majnun on Unsplash

 
Share this