DEV Community

Cover image for How to test promises with Mocha.
Dany Paredes
Dany Paredes

Posted on • Updated on

How to test promises with Mocha.

“The promises”, is a common task for javascript developer for 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 the 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",
  },
]
Enter fullscreen mode Exit fullscreen mode

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 simulate the async process.

Our promise 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 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 }
Enter fullscreen mode Exit fullscreen mode

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, if you are using async and await to handle your async code, we can do the same for testing.

The it declaration should be async to able to use the await until the promises are resolved or rejected, write a test for Find the player and another for getting the error is 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')
        })
    })})
Enter fullscreen mode Exit fullscreen mode

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 total with 21 IVA
  Get teams from API
    ✓ Find team by team player (1003ms)
    ✓ Throw a error if player not found (1004ms)
  4 passing (2s)
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)