How to test promises with Mocha.
Tags: testing, javascript, codenewbie
Published: 2020-08-12 18:42:24

[“The promises”](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), 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](https://github.com/danywalls/testing-js-with-mocka) 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.

```javascript
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 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.

```javascript
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**, 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.

```javascript
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.

```bash
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!

Photo by <a href="https://unsplash.com/@mufidpwt?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Mufid Majnun</a> on <a href="https://unsplash.com/s/photos/testing?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>