【问题标题】:Sinon Stub/Spy on local functions in unit testingSinon Stub/Spy 在单元测试中的本地函数
【发布时间】:2017-09-08 20:28:01
【问题描述】:

我使用 es6 模块和 Karma/Mocha/Sinon/Chai 进行单元测试。如果我在另一个 es6 模块中调用了一个 es6 模块,我可以对第二个 es6 模块进行存根/监视,如下所示:

module-a.js

export function a() {
     // do something
}

module-b.js

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

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

使用上面的代码,我可以监视 moduleA.a() 并确定它何时被调用,并存根 moduleA.a() 并强制返回特定值。

但是,如果我遇到这种情况,我就无法监视或存根:

module-a.js

export function a() {
     // do something
}

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

如果我在本例中尝试 spy/stub 函数 a(),则永远不会调用 Sinon 中的 spy/stub/这是一种很常见的情况,所以有没有人找到一种方法来 spy/stub 本地函数?

谢谢!

【问题讨论】:

标签: javascript unit-testing karma-runner sinon


【解决方案1】:

我遇到了类似的问题,我使用以下方法添加默认导出,它是所有命名函数导出的命名变量包装器。然后,您使用该默认导出对象引用为您的模块内函数调用添加前缀。在您的测试中,您导入默认导出,然后能够使用尊重存根行为的模块内函数调用存根:

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

【讨论】:

    猜你喜欢
    • 2018-07-19
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2017-02-12
    • 2017-07-11
    相关资源
    最近更新 更多