node.js - 监视导入的函数
问题描述
我想监视一个在需要文件时立即执行的函数。在下面的示例中,我想监视 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 在执行后会被存根。如果我将第一行包装在一个函数中并在我的测试中执行该函数,则上面的示例有效。但这不是我想要的。有人知道如何存根这些方法吗?
解决方案
在这个问题上,我们可以使用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)
})
}
参考:
希望能帮助到你
推荐阅读
- python - 使用 Python 正则表达式替换特定上下文中的所有匹配项
- python - 不和谐.py | 当机器人离开时,被踢,被服务器禁止
- python - WebScrape 所有相关的 URL/Hrefs
- html - Wordpress 页面标题中的斜体导致浏览器中出现奇怪的 HTML
- maven - AWS CodeCommit 和 Maven 发布插件
- json - json 算不算数据结构?如果不是,那么 JSON 的本质是什么?
- android - issue with addOnCompleteListener solved! -> running into W/System: Ignoring header X-Firebase-Locale because its value was null
- docker - 模拟 docker 节点之间的网络延迟
- android - 为整个屏幕设置 onClickListener
- db2-luw - DB2 LUW 数据库中的 JSON 查询执行语法错误