【问题标题】:Sinon Stub is not working in mochaSinon Stub 在 mocha 中不工作
【发布时间】:2015-10-08 13:07:53
【问题描述】:

我正在尝试使用 sinon 存根来模拟一个函数,但它没有按预期工作,有人可以解释如何修复它

在 customFunc.js 文件之一中,我有类似的功能

function test() {
  return 'working good';
}
exports.test = test;

function testFunction(data, callback) {
  var sample = test();
  if(sample === 'test') {
    return callback(null, sample);
  }
  else {
    return callback(null, 'not working');
  }
}
exports.testFunction = testFunction;

我正在尝试使用 mocha 测试 testFunction,我尝试像这样使用 sinon 来存根测试函数

it('testing sinon', function(done) {
  var stub = sinon.stub(customFunc,'test').returns('working');

  customFunc.testFunction('test', function(err, decodedPayload) {
    decodedPayload.should.equal('working');
    done();
  });
});

sinon 是否有效,我应该始终将“工作”作为输出,但它没有发生,请告诉我如何模拟 test() 函数。

【问题讨论】:

    标签: unit-testing mocha.js sinon stub


    【解决方案1】:

    您的 sinon 存根看起来不错,但您在测试中的预期不正确。如果 'test' 函数返回 'working' (因为存根),那么将发生以下情况:

      var sample = test(); // sample = 'working'
      if(sample === 'test') { // will evaluate false
        return callback(null, sample);
      }
      else {
        return callback(null, 'not working'); // will return 'not working'
      }
    

    所以这自然会评估为假。

    decodedPayload.should.equal('working');
    

    【讨论】:

    • 感谢您的回复,对我来说存根不起作用。如果您认为代码不正确,请告诉错误在哪里。如果 sinon 不工作,我们可以使用其他任何模块吗
    • @UserJ 我认为您没有看到 KJ3 试图向您展示的内容:您正在创建一个返回“工作”但将该值与 if 语句中的“测试”进行比较的存根。您应该将存根更改为返回“测试”而不是“工作”,或者您应该更改您在 if 中所做的检查。
    猜你喜欢
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 2019-09-30
    • 2019-01-11
    相关资源
    最近更新 更多