简体   繁体   English

诗农不适用于导出功能

[英]Sinon not working for exported function

I have a really simple JS lib (called trysinon.js) that looks like this:我有一个非常简单的 JS 库(称为 trysinon.js),如下所示:

export function foo() {
  bar();
}

export function bar() {
 return 2;
}

And I have the following test我有以下测试

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);
  });
});

And the test is failing.并且测试失败。 How can I ensure the test passes?如何确保测试通过?

Because in foo() , you called bar() which is inner function of trysinon.js.因为在foo() ,你调用了bar() ,它是 trysinon.js 的内部函数。 This bar() is different with the bar() you stubbed which is exported.这个bar()与导出的bar()不同。 The best way is to change trysinon to class, or called exported bar() in foo() as following.最好的方法是将trysinon更改为 class,或者在foo()调用导出的bar()如下。

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

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

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

Hope this can help you.希望这可以帮到你。

I use arrow function instead, and it works.我改用箭头函数,它有效。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM