Unit test bluebird Promise.all with Mocha/Chai

Viewed 364

What would be the proper way to unit test this getall function using mocha/chai? I'm having a hard time understanding what to expect with Promise.all.

const Promise = require('bluebird');
const someApiService = require('./someapiservice');
const _ = require('underscore');

function getall(arr) {
  let promises = _.map(arr, function(item) {
    return someApiService(item.id);
  });
  return Promise.all(promises);
}
1 Answers

We should stub standalone function someApiService use link seams. This is the CommonJS version, so we will be using proxyquire to construct our seams. Additionally, I use sinon.js to create the stub for it.

E.g.

getall.js:

const Promise = require('bluebird');
const someApiService = require('./someapiservice');
const _ = require('underscore');

function getall(arr) {
  let promises = _.map(arr, function (item) {
    return someApiService(item.id);
  });
  return Promise.all(promises);
}

module.exports = getall;

someapiservice.js:

module.exports = function someApiService(id) {
  return Promise.resolve('real data');
};

getall.test.js:

const proxyquire = require('proxyquire');
const sinon = require('sinon');
const { expect } = require('chai');

describe('45337461', () => {
  it('should pass', async () => {
    const someapiserviceStub = sinon.stub().callsFake((id) => {
      return Promise.resolve(`fake data with id: ${id}`);
    });
    const getall = proxyquire('./getall', {
      './someapiservice': someapiserviceStub,
    });
    const actual = await getall([{ id: 1 }, { id: 2 }, { id: 3 }]);
    expect(actual).to.deep.equal(['fake data with id: 1', 'fake data with id: 2', 'fake data with id: 3']);
    sinon.assert.calledThrice(someapiserviceStub);
  });
});

unit test result:

  45337461
    ✓ should pass (2745ms)


  1 passing (3s)

-------------------|---------|----------|---------|---------|-------------------
File               | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------------|---------|----------|---------|---------|-------------------
All files          |   88.89 |      100 |   66.67 |   88.89 |                   
 getall.js         |     100 |      100 |     100 |     100 |                   
 someapiservice.js |      50 |      100 |       0 |      50 | 2                 
-------------------|---------|----------|---------|---------|-------------------
Related