【问题标题】:mocha / sinon stub restore not workingmocha / sinon 存根恢复不起作用
【发布时间】:2018-03-06 15:58:10
【问题描述】:

我的第一个节点测试脚本。我正在使用 Mocha 和 Sinon 来测试一个最终发送到队列的函数。 Node v8.1.3、Mocha 5.0.2、sinon 4.4.2。

var assert = require('assert');
var sinon = require('sinon');
var uut = require('../util');
var stub;

describe('processWantedItemToQueue', function() {
    beforeEach(function() {
      stub = sinon.stub(uut, 'processWantedItemToQueue').returns(true);
    });

    afterEach(function() {
      uut.processWantedItemToQueue.restore();
    });

    it('should not push the item to the queue', function() {
      assert.equal(uut.processWantedItemToValidQueue("a", "q1"), false);
    });

    it('should push the item to the queue', function() {
      assert.equal(uut.processWantedItemToValidQueue("a", "aws"), true);
    });
});

这是我的输出:

> mocha
  processWantedItemToQueue
ignoring queue q1
    ✓ should not push the item to the queue
    1) should push the item to the queue


  1 passing (34ms)
  1 failing

  1) processWantedItemToQueue
       should push the item to the queue:
     ReferenceError: processWantedItemToQueue is not defined
      at Object.processWantedItemToValidQueue (util.js:36:20)
      at Context.<anonymous> (test/test.js:20:24)

我对存根有一些误解。为什么我的第二次测试没有找到存根?

我的 util.js 看起来像这样:

module.exports = {
  processWantedItem: function(item) {
  ...
  },
  processWantedItemToQueue: function(item, queue) {
  ...
  },
  processWantedItemToValidQueue: function(item, queue) {
  ...
  }
}

【问题讨论】:

    标签: node.js mocha.js sinon


    【解决方案1】:

    看起来这不是您的存根问题,而是您的processWantedItemToValidQueue 实现问题;很可能您实际上只是在第二种情况下尝试调用processWantedItemToQueue,但processWantedItemToQueue 正如您所定义的那样,它不会在其他函数的范围内。不过,可以肯定的是,您必须展示您对 processWantedItemToValidQueue 的实现。

    【讨论】:

    • 我也有同样的想法。将我的 uut 函数移动到一个模块中,以便我可以将它们导出以进行测试,从而使它们在模块中不可见。以此为前缀。修复。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    • 2020-02-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    相关资源
    最近更新 更多