【问题标题】:sinon stub error "attempted to wrap undefined property of job as function"sinon 存根错误“试图将作业的未定义属性包装为函数”
【发布时间】:2018-02-18 11:00:25
【问题描述】:

我正在尝试使用 sinon stub 来测试我的函数,该函数包含两个名为 job 和 job1 的变量。如何给它们临时值以避免函数值。

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

function testFunction() {
  var job = this.win.get.value1   //test
  var job1 = this.win.get.value2 // test1
  if(job === 'test' && job1 === 'test1') {
    return true;
  }
    return false; 
}

我正在尝试使用 karma 测试 testFunction,我尝试使用我的值来存根两个值,以便它可以覆盖函数值

it('should test my function', function(done) {
  var stub = sinon.stub('job','job1').values('test','test1');
  myFunction.testFunction('test', function(err, decodedPayload) {
    decodedPayload.should.equal(true);
    done();
  });
});

我收到错误“试图将作业的未定义属性包装为函数”

【问题讨论】:

    标签: unit-testing mocking sinon stub


    【解决方案1】:

    首先,您可以将 testFunction 简化为以下内容。

    function testFunction() {
      return this.win.get.value1 === 'test' && this.win.get.value2 === 'test1';
    }
    

    这里没有异步发生,所以在你的测试中你不需要使用 done()。

    Sinon 的“存根”文档建议您应该使用 sandbox 功能来存根非函数属性。

    从您的问题中不清楚您的“this”上下文是什么,所以我假设您的测试已经用名称“myFunction”(您的测试暗示)实例化了您正在测试的任何内容。

    还不清楚“赢”和“得到”是什么,因此假设它们是对象。

    不要忘记 restore() 沙箱,以免污染后续测试。

    it('should test my function', function() {
      var sandbox = sinon.sandbox.create();
      sandbox.stub(myFunction, 'win').value({
        get: {
          value1: 'test',
          value2: 'test1',
        }
      });
    
      myFunction.testFunction().should.equal(true);
    
      sandbox.restore();
    });
    

    【讨论】:

      猜你喜欢
      • 2020-07-19
      • 1970-01-01
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多