gpt4 book ai didi

javascript - Proxyquire 没有 stub 我需要的类(class)

转载 作者:数据小太阳 更新时间:2023-10-29 05:21:34 26 4
gpt4 key购买 nike

我有一个类 AProvider 需要 './b.provider'

const BProvider = require('./b.provider');

class AProvider {
static get defaultPath() {
return `defaults/a/${BProvider.getThing()}`;
}
}

module.exports = AProvider;

b.provider.jsa.provider.js 相邻,看起来像

global.stuff.whatever = require('../models').get('Whatever'); // I didn't write this!

class BProvider {
static getThing() {
return 'some-computed-thing';
}
}
module.exports = BProvider;

在我的测试中,我使用 proxyquire 模拟出 ./b.provider 如下:

import { expect } from 'chai';
import proxyquire from 'proxyquire';

describe('A Provider', () => {
const Provider = proxyquire('../src/a.provider', {
'./b.provider': {
getThing: () => 'b-thing'
},
});

describe('defaultPath', () => {
it('has the expected value', () => {
expect(Provider.defaultPath).to.equal('defaults/a/b-thing')
});
});
});

然而,当我运行测试时,BProvider 仍然需要实际的 './b.provider' 而不是 stub 和 BProvider 对 global.stuff 的引用。 whatever 抛出错误。

为什么这不起作用?

最佳答案

为什么会这样,答案如下

proxyquire 在将其 stub 之前仍然需要底层代码。它这样做是为了启用调用。

解决方案只是明确禁止调用。

测试变成:

import { expect } from 'chai';
import proxyquire from 'proxyquire';

describe('A Provider', () => {
const Provider = proxyquire('../src/a.provider', {
'./b.provider': {
getThing: () => 'b-thing',
'@noCallThru': true
},
});

describe('defaultPath', () => {
it('has the expected value', () => {
expect(Provider.defaultPath).to.equal('defaults/a/b-thing')
});
});
});

运行此测试效果很好。

关于javascript - Proxyquire 没有 stub 我需要的类(class),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42550134/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com