首页 > 解决方案 > 监视导入的函数

问题描述

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

代码.ts

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

测试.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 在执行后会被存根。如果我将第一行包装在一个函数中并在我的测试中执行该函数,则上面的示例有效。但这不是我想要的。有人知道如何存根这些方法吗?

标签: node.jsunit-testingmockingsinon

解决方案


在这个问题上,我们可以使用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)
  })
}

参考:

希望能帮助到你


推荐阅读