avatar

proxyquire偷换import

最近在写一个延迟handle burst event的东西,我要延迟30s访问,让docusign能把它的burst limit腾出来,防止它爆掉。但是我写了30s的延迟的话,我的test case就需要跑很长时间,因为test case也会跟着延迟30s。而且我写了这个test case到时候merge了相当于大家的test时间全都要+30s,这就很过分。这个时候就可以使用proxyquire来置换掉import信息,比如我原来有:

1
export const BURST_LIMIT_EXCEED_ERR_DELAY = 30000;

这行在我的docusignDefenition.ts文件中,我在docusignBurstHandler.ts中引用了它来作为我的delay毫秒数,eg.引用如下:

1
2
3
4
5
import { BURST_LIMIT_EXCEED_ERR_DELAY } from '../definitions/DocusignDefinitions';

export async function handleDocusignBurst(ctx: Ictx): Promise<void> {
console.log(BURST_LIMIT_EXCEED_ERR_DELAY);
}

而到了docusignBurstHandlerTests.ts里,我们就可以用proxyquire来把这个import给替换掉:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import * as sinon from 'sinon';
import * as proxy from 'proxyquire';
import { handleDocusignBurst } from '../../../lib/eSign/external/docusignBurstHandler';

const sandbox = sinon.sandbox.create();
const proxyquire = proxy.noCallThru();

describe('xxxx', function() {
afterEach(function() {
sandbox.restore();
});

it('xxxxx', async function() {
const BURST_LIMIT_EXCEED_ERR_DELAY = 10;
const burstTimeMock = sandbox.mock(BURST_LIMIT_EXCEED_ERR_DELAY);
const handleDocusignBurstStab = proxyquire('../../../lib/eSign/external/docusignBurstHandler', {
'../definitions/DocusignDefinitions': burstTimeMock,
});
handleDocusignBurstStab.handleDocusignBurst();
});
});

参考:https://ozmoroz.com/2017/09/mocking-es6-dependencies-1

文章作者: 8128
文章链接: http://8128.me/2020/05/19/proxyquire%E5%81%B7%E6%8D%A2import/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 8128's Blog
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论