【问题标题】:How to mock a function defined with this keyword using sinon?如何使用 sinon 模拟使用 this 关键字定义的函数?
【发布时间】:2023-03-20 00:20:02
【问题描述】:

我有一个函数 foo

var foo = function(){
    this.doRandomStuff = function(callback){
      //do Something
      callback(false);
    }
}
var bar = function(){
    var fooInstance = new foo();
    fooInstance.doRandomStuff(function(val){
      //do Something with val
    })
}

我想为 bar 函数编写测试,为此我使用 mocha 和 sinon。

describe("Foo Test",function(){
      it("testing foo",function(done){
         var instance = new foo();

         sinon.stub(instance,'doRandomStuff').callsArgWith(0,true); // This Doesn't work
         sinon.stub(foo,'doRandomStuff').callsArgWith(0,true); // This also Doesn't work

         bar();
         done();
      })
});

我得到以下异常:

TypeError: 不能存根不存在的自己的属性 doRandomStuff

【问题讨论】:

  • 您无法测试此代码。您正在 bar 函数中创建 foo 的新实例。所以你没有这个实例的访问权限。为了使其可测试,您可以将 foo 的实例传递给 bar 函数。

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


【解决方案1】:

使其更具可测试性的替代方法是模块方法,如下所示:

foo.js

function doRandomStuff(callback) {
  callback(false);
}

module.exports = {
  doRandomStuff
}

bar.js

const foo = require('./foo');

module.exports = function() {
  foo.doRandomStuff(function(val) {
    console.log('test val', val); // for testing purpose
  })
}

test.js

const sinon = require('sinon');
const foo = require('./foo');
const bar = require('./bar');

describe('Foo Test', function() {
  it("testing foo",function(done){
    sinon.stub(foo, 'doRandomStuff').callsArgWith(0,true); 

    bar(); // output: "test val true"
    done();
 });
});

【讨论】:

    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 2021-09-13
    • 2013-01-12
    • 2015-02-17
    相关资源
    最近更新 更多