【问题标题】:Sinon stub method calling from another file从另一个文件调用 Sinon 存根方法
【发布时间】:2018-10-29 11:18:53
【问题描述】:

我正在尝试在我的项目中设置单元测试。为此,我使用 mocha chai 和 sinon 库。我使用的是 NodeJs 服务器版本 8。

版本:

诗乃:“7.1.0” 摩卡:“5.1.0” 柴:“4.2.0”

我想存根在另一个文件中声明的方法。

这是一个例子:

- a.js
   exports.FnA(return FnB())
- b.js
   exports.FnB()

我想从 b.js 文件中存根方法 FnB(),这样我就可以测试 FnA() 而不管 FnB() 返回。

这是我尝试过的:

beforeEach(() => {
            this.FnBStub = sinon.stub(b, 'FnB').returns('mocked');
        });

afterEach(() => this.FnBStub.restore());

it('should mocked FnB function', () => {
            try {
                console.log(b.FnB()); //returns 'mocked'
                console.log(a.FnA()); //return error from FnB() execution ...
            } catch (e) {
                console.log(e);
            }
        });

它确实存根方法 FnB() 但仅当我从 b 文件的实例调用它时。所以当我调用 FnA() 时,存根似乎消失了......

我错过了什么?

非常感谢您的帮助,谢谢:)

编辑

a.js 示例:

const FnB = require('./FnB)

exports.FnA = data => {
    const limit = data.releases.update ? 60 : 20;
    return FnB(data.ref, limit)
};

b.js 示例:

exports.FnB = (ref, page, query) => {
   //API call
}

testFile.js 示例:

const a = require('../a')
const b = require('../b')

beforeEach(() => {
            this.FnBStub = sinon.stub(b, 'FnB').returns('mocked');
        });

afterEach(() => this.FnBStub.restore());

it('should mocked FnB function', () => {
            try {
                console.log(b.FnB()); //returns 'mocked'
                console.log(a.FnA()); //return error from FnB() execution ...
            } catch (e) {
                console.log(e);
            }
        });

正如我所说,我想对这个 FnB 调用方法进行存根,然后检查是否使用正确的参数调用了这个方法。

【问题讨论】:

  • 能否分享文件a.js中的相关代码
  • @tbking 是的,我更新了我的问题
  • 它仍然没有显示如何从文件 b.js 导入 FnB 函数
  • @tbking 为我的误解道歉
  • 不错。我根据最新的编辑回答了这个问题。

标签: node.js unit-testing testing sinon-chai


【解决方案1】:

如果被导出的模块是一个函数本身而不是一个对象的一部分,你不能直接存根它。

您需要使用proxyquire 之类的内容。您的测试代码将如下所示:

const FnBstub = sinon.stub();
const proxyquire = require('proxyquire');
const a = proxyquire('../a', {
    FnB: FnBstub
});
const b = require('../b');

更多信息,请看这里:https://github.com/sinonjs/sinon/issues/664

【讨论】:

    猜你喜欢
    • 2016-02-18
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-18
    相关资源
    最近更新 更多