【问题标题】:Will nested function be called in mocha unit test after stubbing :AssertionError: expected 'some data' to equal 'stubbed string'存根后是否会在 mocha 单元测试中调用嵌套函数:AssertionError:预期“某些数据”等于“存根字符串”
【发布时间】:2020-06-06 05:50:53
【问题描述】:

我是使用 mocha 和 sinon 进行单元测试的新手,为了了解更多信息,我设置了一个函数来返回一些字符串,在我的代码中我将此函数称为内部函数。我的测试是查看存根返回字符串是否分配给变量。请看代码sn-p了解更多

file.specjs

let sinon = require("sinon");
let filejs = require('./file.js');
let expect = require ("chai").expect;

it('should run only the outer function' ,function() {

// I try to stub my function here
sinon.stub(filejs,'test1').callsFake ((someArg) => {
  return "stubbed string";
});

// Now I will call my test outer function
   filejs.test();
  expect(filejs.param).to.equal("stubbed string");

})


    let param;
    module.exports = {
         test,
         test1
    }

    function test () {
      module.exports.param = test1();
    }

    function test1() {
       console.log("should not be called);
       let data = "some data";
       return data; 
    }

由于我已经对函数 test1 进行了存根,我不希望调用它,并将 test1 的返回值分配给 param,并且由于我们伪造了函数以返回不同的字符串,所以我希望设置此字符串到参数变量。

但是当我运行测试时,我看到了这个错误

AssertionError: 预期“某些数据”等于“存根字符串”

【问题讨论】:

  • 对不起,我忘了在规范文件中添加 chai expect :)
  • 使用module.exports 而不是module.export
  • 感谢 Doug Coburn :) 我还修改了我的代码 sn-p,我没有将任何参数传递给函数测试
  • 我改变了我的问题,我现在看到断言错误,存根函数不会替换字符串值
  • 我回答得太快了。我的回答不正确。

标签: javascript node.js unit-testing mocha.js sinon


【解决方案1】:

尝试以下编辑...

    function test () {
      module.exports.param = module.exports.test1();
    }

为了有机会工作而努力做的事情。您需要sinon 来修改module.exports,并且被测代码需要从该对象中读取test1()。它可能需要更深地嵌套才能修改它......我不知道。我在使用sinon.stub(require('./something'))时遇到了麻烦

我想我让它在 repl.it 中工作 https://repl.it/repls/NegativeEnragedMainframe

【讨论】:

    猜你喜欢
    • 2020-07-12
    • 2016-07-11
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    • 2017-04-19
    • 2015-12-21
    相关资源
    最近更新 更多