从同一个模块调用存根模块功能 [英] Stub module function called from the same module

查看:141
本文介绍了从同一个模块调用存根模块功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想不出一种方法来对从定义此函数的同一模块中调用的函数进行存根(存根似乎不起作用).这是一个示例:

I can't figure out a way to stub a function called from within the same module this function is defined (the stub does not seem to work). Here's an example:

myModule.js:

myModule.js:

'use strict'

function foo () {
  return 'foo'
}

exports.foo = foo

function bar () {
  return foo()
}

exports.bar = bar

myModule.test.js:

myModule.test.js:

'use strict'

const chai = require('chai')
const sinon = require('sinon')

chai.should()

const myModule = require('./myModule')

describe('myModule', () => {
  describe('bar', () => {
    it('should return foo', () => {
      myModule.bar().should.equal('foo') // succeeds
    })

    describe('when stubbed', () => {
      before(() => {
        sinon.stub(myModule, 'foo').returns('foo2') // this stub seems ignored
      })

      it('should return foo2', () => {
        myModule.bar().should.equal('foo2') // fails
      })
    })
  })
})

这让我想起了(几乎)不可插拔的Java静态函数.

This reminds me of Java static functions which are not stubbable (almost).

有什么想法可以实现我想要做的事情吗?我知道在另一个模块中提取foo是可以的,但这不是我要在这里执行的操作.我还知道在bar方法中使用关键字this调用foo也是可行的,我很困惑在这种情况下使用̀ this(因为我没有使用OOP)

Any idea how to achieve what I'm trying to do? I know that extracting foo in a different module will work, but that's not what I'm trying to do here. I'm also aware that invoking foo in the bar method with the keyword this will also work, I'm puzzled toward the use of ̀this in this context (since I'm not using OOP).

推荐答案

我刚刚对此进行了测试.它就像魅力一样.

I just tested this. And it works like charm.

'use strict'

function foo () {
  return 'foo';
}

exports.foo = foo;

function bar () {
  return exports.foo(); // <--- notice
}

exports.bar = bar;

说明

当您执行sinon.stub(myModule, 'foo').returns('foo2')时,sinon将从myModule.js内部对exported对象的foo而不是实际的foo函数进行存根...正如您必须知道的那样,可以从以下位置访问foo在模块外部.因此,当您设置exports.foo时,导出的对象exports.foo将存储foo的引用.并且当您呼叫sinon.stub(myModule, 'foo').returns('foo2')时,sinon将存根exports.foo而不是实际的foo

when you do sinon.stub(myModule, 'foo').returns('foo2') then sinon stubs the exported object's foo not the actually foo function from inside your myModule.js ... as you must know, foo is in accessible from outside the module. So when you set exports.foo, the exported object exports.foo stores the ref of foo. and when you call sinon.stub(myModule, 'foo').returns('foo2'), sinon will stub exports.foo and not the actual foo

希望这很有道理!

这篇关于从同一个模块调用存根模块功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆