【问题标题】:Sinon not working for exported functionSinon 不适用于导出功能
【发布时间】:2017-10-27 05:40:27
【问题描述】:

我有一个非常简单的 JS 库(称为 trysinon.js),如下所示:

export function foo() {
  bar();
}

export function bar() {
 return 2;
}

我有以下测试

import expect from 'expect';
import sinon from 'sinon';
import * as trysinon from 'trysinon';

describe('trying sinon', function() {
  beforeEach(function() {
    sinon.stub(trysinon, 'bar');
  });

  afterEach(function() {
    trysinon.bar.restore();
  });

  it('calls bar', function() {
    trysinon.foo();
    expect(trysinon.bar.called).toBe(true);
  });
});

测试失败了。如何确保测试通过?

【问题讨论】:

标签: javascript mocha.js sinon


【解决方案1】:

因为在foo()中,你调用了bar(),这是trysinon.js的内部函数。这个bar() 与你导出的bar() 不同。最好的办法是将trysinon改为class,或者在foo()中调用exportedbar()如下。

function bar() { return 2; }
module.exports.bar = bar;

function foo() {
  module.exports.bar();
}
module.exports.foo = foo;

然后你可以用sinon.stub(trysinon, 'bar').returns(2)存根bar()

希望对你有帮助。

【讨论】:

    【解决方案2】:

    我用箭头函数代替,它有效。

    export const foo = () => {
      bar();
    }
    
    export const bar = () => {
     return 2;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-31
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 2015-11-27
      • 2016-10-08
      • 1970-01-01
      • 2014-10-12
      • 1970-01-01
      相关资源
      最近更新 更多