监视导入函数
Spy on imported function
我想监视一个在需要文件时立即执行的函数。在下面的示例中,我想监视 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)
})
}
stubing 不起作用。我认为这是一个时间问题。 Bar 在执行后会被存根。如果我将第一行包装在一个函数中并在我的测试中执行该函数,上面的示例就可以工作。但这不是我想要的。有人知道如何存根这种方法吗?
我认为你的问题是你从来没有导入你正在执行 const foo = bar() 的文件。您只是导入 bar,仅此而已!尝试在 it 块中导入或要求您的文件!那应该触发 bar() ,所以测试应该通过!
it('should work', () => {
const foo = require(‘your_foo_file’)
assert.isTrue(bar.calledOnce)
})
再见!
在这个问题上,我们可以使用 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)
})
}
参考:
希望对您有所帮助
我想监视一个在需要文件时立即执行的函数。在下面的示例中,我想监视 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)
})
}
stubing 不起作用。我认为这是一个时间问题。 Bar 在执行后会被存根。如果我将第一行包装在一个函数中并在我的测试中执行该函数,上面的示例就可以工作。但这不是我想要的。有人知道如何存根这种方法吗?
我认为你的问题是你从来没有导入你正在执行 const foo = bar() 的文件。您只是导入 bar,仅此而已!尝试在 it 块中导入或要求您的文件!那应该触发 bar() ,所以测试应该通过!
it('should work', () => {
const foo = require(‘your_foo_file’)
assert.isTrue(bar.calledOnce)
})
再见!
在这个问题上,我们可以使用 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)
})
}
参考:
希望对您有所帮助