【问题标题】:Stubbing out a promise inside a method using chai and sinon使用 chai 和 sinon 在方法中删除一个 Promise
【发布时间】:2017-02-21 03:17:22
【问题描述】:

我的被测函数大致是这样的;

  function doThing(data, callback) {

    externalService.post('send').request(data)
        .then(() => {
          if (callback) { callback(); }
        })
        .catch((message) => {
          logger.warn('warning message');
          if (callback) { callback(); }
        });
  }

我正在尝试使用 Chai 和 Sinon 进行测试。

我尝试过遵循不同的指南,我目前的咒语看起来像;

const thingBeingTested = require('thing-being-tested');
const chai = require('chai');
const sinon = require('sinon');
require('sinon-as-promised');
const sinonChai = require('sinon-chai');
const expect = chai.expect;

var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
chai.use(sinonChai);

describe('The Thing', () => {  
  it('should run a callback when requested and successful', done => {

    const externalService = { post: { request: sinon.stub() } };
    const callback = sinon.spy();

    externalService.post.request.resolves(callback);

    doThing({...}, callback);
    expect(callback).to.have.been.called;
    done();
  });
});

我无法正确删除externalService.post。任何帮助将不胜感激。

我对 Chai 和 Sinon 完全陌生——所以完全期望自己会做一些愚蠢的事情。

【问题讨论】:

  • 您是否考虑过使用代理 nodejs 所需的proxyquire 以便在测试期间允许覆盖依赖项?它是在nodejs 中测试时使用的有用工具,并且在我看来确实使测试更简单。
  • 谢谢@hyprstack——我从没听说过。我将看看它是否对这个用例有意义(在我的示例中,我进行了一次测试,但当然还有一些其他的事情需要练习)。

标签: node.js sinon chai sinon-chai


【解决方案1】:

您的doThing 函数无法从您的测试中访问const externalService。我会假设你的主文件有类似

const externalService = require('./external_service');

得到它。

在您的测试中,您也应该得到相同的externalService

describe(..., () => {
    it(..., () => {
        // adjust the path accordingly
        const externalService = require('./external_service');

然后模拟它的方法:

sinon.stub(externalService, 'post').returns({
    request: sinon.stub().resolves(callback)
});

那你就可以拨打doThing分析结果了。

测试完成后,别忘了恢复原来的postby

externalService.post.restore();

【讨论】:

    猜你喜欢
    • 2015-12-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 2017-09-14
    • 2017-06-29
    • 1970-01-01
    相关资源
    最近更新 更多