Danywalls

Testing promises with Mocha.

May 28, 2019

In my post about testing with Mocha, I forget a common task in every javascript developer, “the promises”, its is a common task for make our code run async, but how I can test it ?.

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

I will write a method which return a promise and we will add test for the resolved and rejected promise.

The Fake API

Create a file api.js with a 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 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 team with player is found or the reject with error if not found. Export the function to be used.

getTeamByPlayer is a simple function, it get the player and find into our array, if it found 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 setup the test similar to my preview post.

.. But with just only diference, 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 is resolved or rejected, write a test for Find the player and another for get 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')
        })
    })

})

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)

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!


Dany Paredes

Hi, I'm Dany Paredes, few years ago I was working with .NET, but in my last years I have been focusing in Javascript using Vue , Angular or React. You can read more in Twitter or Github.