【问题标题】:How to sinon spy module export utility functionssinon spy 模块导出实用函数的方法
【发布时间】:2017-02-13 13:16:55
【问题描述】:

在 javascript (ES6) 中,我有一个实用模块,它只包含一些函数,然后在文件末尾,我像这样导出它们:

module.exports = {
  someFunction1,
  someFunction2,
  someFunction3,
}

然后我想为这些函数编写单元测试。一些功能相互依赖;它们以某种方式相互调用,例如,someFunction1 可能调用 someFunction2。没有循环问题。

一切正常,直到我需要监视其中一个函数被调用。我该怎么做?目前我正在使用 Chai 和 Sinon。

在测试文件中,我已将整个文件作为模块导入:

const wholeModule = require('path/to/the/js/file')

最后,我的测试如下所示:

it('should call the someFunction2', (done) => {
  const spy = sinon.spy(wholeModule, 'someFunction2')

  wholeModule.someFunction1() // someFunction2 is called inside someFunction1

  assert(spy.calledOnce, 'someFunction2 should be called once')
  done()
})

问题是,测试失败,因为在 someFunction1 中,直接使用了 someFunction2 函数。我将间谍应用到模块对象的函数中。但这是一个不同的对象。这是 someFunction1 的示例:

function someFunction1() {
  someFunction2()
  return 2;
}

我知道它不起作用的原因,但我不知道在这种情况下使它起作用的最佳做法是什么?请帮忙!

【问题讨论】:

    标签: javascript node.js sinon chai


    【解决方案1】:

    您可以使用rewire 模块。这是一个例子:

    源代码:

    function someFunction1() {
      console.log('someFunction1 called')
      someFunction2();
    }
    
    function someFunction2() {
      console.log('someFunction2 called')
    }
    
    module.exports = {
      someFunction1: someFunction1,
      someFunction2: someFunction2
    }
    

    测试用例:

    'use strict';
    
    var expect = require('chai').expect;
    var rewire = require('rewire');
    var sinon = require('sinon');
    
    var funcs = rewire('../lib/someFunctions');
    
    it('should call the someFunction2', () => {
      var someFunction2Stub = sinon.stub();
      funcs.__set__({
        someFunction2: someFunction2Stub,
      });
    
      someFunction2Stub.returns(null);
    
      funcs.someFunction1();
    
      expect(someFunction2Stub.calledOnce).to.equal(true);
    });
    

    【讨论】:

    • 不错的尝试,但没有奏效 =/。它清楚地调用了假函数。但是当我断言间谍被调用时,它没有被调用
    • @VilleMiekk-oja 编辑后您尝试解决方案了吗?
    • 是的,结果没有区别
    • 我很确定这与我如何 module.export 实用程序函数有关。我这样做的方式是在问题描述中。
    • 恭喜!你的最后一个例子确实有效:)。请删除其余的,因为它们不起作用
    猜你喜欢
    • 2019-09-11
    • 2018-01-25
    • 2017-02-12
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 2017-10-24
    • 2017-04-02
    相关资源
    最近更新 更多