简体   繁体   English

Sinon Stub / Spy在单元测试中的本地功能

[英]Sinon Stub/Spy on local functions in unit testing

I use es6 modules and Karma/Mocha/Sinon/Chai for unit testing. 我使用es6模块和Karma / Mocha / Sinon / Chai进行单元测试。 If I have an es6 module called within another es6 module I am able to stub/spy on that second es6 module, as seen below: 如果我在另一个es6模块中调用了es6模块,我可以对第二个es6模块进行存根/间谍,如下所示:

module-a.js 模块a.js

export function a() {
     // do something
}

module-b.js 模块b.js

import * as moduleA from './module-a';

export function b() {
     // do something
     moduleA.a();
}

With the above code I can spy on moduleA.a() and determine when it was called and stub moduleA.a() and force specific return values. 使用上面的代码,我可以监视moduleA.a()并确定它何时被调用和stub moduleA.a()并强制特定的返回值。

BUT, if I have this situation instead, I cannot spy or stub: 但是,如果我有这种情况,我不能间谍或存根:

module-a.js 模块a.js

export function a() {
     // do something
}

export function b() {
     // do something
     a();
}

If I try to spy/stub function a() in this example the spy/stub in Sinon is never called/ This is a pretty common situation so has anyone found a way to spy/stub the local functions? 如果我在这个例子中试图窥探/存根函数a(),那么Sinon中的spy / stub永远不会被调用/这是一个非常常见的情况,所以有没有人找到一种间谍/存根本地函数的方法?

Thanks! 谢谢!

I had a similar issue and I'm using the following approach where you add a default export that is a named variable wrapper of all of the named function exports. 我有一个类似的问题,我正在使用以下方法,您添加一个默认导出,它是所有指定函数导出的命名变量包装。 You then prefix your intra-module function calls with that default export object reference. 然后,使用该默认导出对象引用为模块内函数调用添加前缀。 In your test you import the default export and are then able to stub with intra-module function calls respecting the stubbed behavior: 在您的测试中,您导入默认导出,然后能够使用模块内函数调用来存根,这些函数调用遵循存根行为:

// MyModule.js
let MyModule;

export function myfunc2() { return 2; }
export function myfunc1() { return MyModule.myfunc2(); }

export default MyModule = {
  myfunc1,
  myfunc2
}

// tests.js
import MyModule from './MyModule'

describe('MyModule', () => {
  const sandbox = sinon.sandbox.create();
  beforeEach(() => {
    sandbox.stub(MyModule, 'myfunc2').returns(4);
  });
  afterEach(() => {
    sandbox.restore();
  });
  it('myfunc1 is a proxy for myfunc2', () => {
    expect(MyModule.myfunc1()).to.eql(4);
  });
});

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

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