node.js - 使用 Mocha/Chai 对 bluebird Promise.all 进行单元测试

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

最佳答案

我们应该 stub 独立函数 someApiService 使用 link seams .这是 CommonJS 版本,所以我们将使用 proxyquire构建我们的接缝。此外,我使用 sinon.js为它创建 stub 。

例如

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

关于node.js - 使用 Mocha/Chai 对 bluebird Promise.all 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45337461/

相关文章:

javascript - Mongodb 到 Android 应用程序

java - 如何在 Jooq 中初始化和创建 ResultSet 和 Record?

node.js - Koa 如何帮助避免 "monkey patching"以及 "Hapi"或 "Express"如何不做同样的事情?

express - PassportJS 本地无限循环认证

javascript - Browserify 转换插件用于评估 IIFE 并在捆绑期间替换为其结果

javascript - Node.js child.stdin.write 不起作用

javascript - PHP 的 `hex2bin` 的 Node.js/JS 实现返回错误结果。如何得到相同的结果?

visual-studio-2010 - Ninject ToFactory 适用于 Resharper 单元测试,但不适用于 NCrunch

typescript - 是否可以在 Jasmine 单元测试中修改或模拟 Typescript 类使用的 Inversify 容器?

javascript - 使用 Express 合并、缩小和提供 JavaScript 文件,但响应未压缩