如何在Sinon中模拟内部函数?

问题描述 投票:4回答:1

假设我有两个函数,foobar中调用。我有一个流星应用程序,所以我决定使用流星mocha包与sinonchai而不是jest

// foo.js

const foo = () => // call to a google maps api;
export default foo;


// bar.js

const bar = (x) => {
  foo();
  ...
};
export default bar;

在这种情况下,模拟foo的正确方法是什么?

目前我已经提出了以下解决方案:

import foo from 'path/to/foo.js'
import bar from 'path/to/bar.js'

describe('my test suite', function() {
  it('should pass the test', function() {
    foo = spy();
    bar(5);
    assert(foo.calledOnce);
  });
}); 

以下代码有效,但重新定义foo是否正确?

UPDATE

此外,不可能以这种方式创建模拟或存根,这让我觉得Sinon不适合模拟独立功能

unit-testing meteor sinon
1个回答
2
投票

Sinon适用于独立的JavaScript函数。

以下是如何在Sinon间谍中包装模块的默认导出的示例:

import * as sinon from 'sinon';
import * as fooModule from 'path/to/foo.js'
import bar from 'path/to/bar.js'

describe('my test suite', function() {
  it('should pass the test', function() {
    const spy = sinon.spy(fooModule, 'default');  // wrap the function in a spy
    bar(5);
    assert(spy.calledOnce);  // SUCCESS
    spy.restore();  // restore the original function
  });
}); 

以下是如何使用Sinon存根替换模块的默认导出的示例:

import * as sinon from 'sinon';
import * as fooModule from 'path/to/foo.js'
import bar from 'path/to/bar.js'

describe('my test suite', function() {
  it('should pass the test', function() {
    const stub = sinon.stub(fooModule, 'default').returns('something else');  // stub the function
    bar(5);  // foo() returns 'something else' within bar(5)
    assert(stub.calledOnce);  // SUCCESS
    stub.restore();  // restore the original function
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.