【问题标题】:Spy on imported function监视导入的函数
【发布时间】:2018-09-24 11:14:54
【问题描述】:

我想监视一个在需要文件时立即执行的函数。在下面的示例中,我想监视 bar。我有以下文件。

code.ts

import {bar} from 'third-party-lib';
const foo = bar()

test.ts

import * as thirdParty from 'third-party-lib';

describe('test', () => {

  let barStub: SinonStub;      

  beforeEach(() => {
     barStub = sinon.stub(thridParty, 'bar')
  })

  it('should work', () => {
    assert.isTrue(bar.calledOnce)
  })

}

存根不起作用。我认为这是一个时间问题。 Bar 在执行后会被存根。如果我将第一行包装在一个函数中并在我的测试中执行该函数,则上面的示例有效。但这不是我想要的。有人知道如何存根这些方法吗?

【问题讨论】:

  • 你使用什么测试框架? (看起来像Jest,对吗?)

标签: node.js unit-testing mocking sinon


【解决方案1】:

在这个问题上,我们可以使用 proxyquire 来存根第三方库,如下所示:

import * as thirdParty from 'third-party-lib';
const proxyquire = require('proxyquire');

const barStub: SinonStub = sinon.stub();
proxyquire('./your-source-file', {
  'third-party-lib': { bar: barStub } 
});

describe('test', () => {
  it('should work', () => {    
    assert.isTrue(barStub.calledOnce)
  })
}

参考:

希望对你有帮助

【讨论】:

    【解决方案2】:

    我认为你的问题是你永远不会导入你正在执行 const foo = bar() 的文件。您只是在导入 bar,仅此而已!尝试在 it 块中导入或要求您的文件!这应该触发 bar() ,所以测试应该通过!

    it('should work', () => {
    const foo = require(‘your_foo_file’)
    assert.isTrue(bar.calledOnce)
    })
    

    再见!

    【讨论】:

      猜你喜欢
      • 2020-12-27
      • 2017-12-20
      • 2019-07-27
      • 2018-11-24
      • 2022-08-17
      • 2019-02-16
      • 2023-04-04
      • 2015-12-29
      相关资源
      最近更新 更多