单位测试蓝鸟Promise.all与摩卡/柴

时间:2017-07-26 21:07:32

标签: node.js unit-testing express bluebird

使用mocha / chai对这个getall函数进行单元测试的正确方法是什么?我很难理解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 个答案:

答案 0 :(得分:0)

我们应该存根独立函数 someApiService 使用 link seams。这是 CommonJS 版本,因此我们将使用 proxyquire 来构建接缝。此外,我使用 sinon.js 为其创建存根。

例如

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);
  });
});

单元测试结果:

  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                 
-------------------|---------|----------|---------|---------|-------------------