我有一个类AProvider,它需要'./b.provider'。
const BProvider = require('./b.provider');
class AProvider {
static get defaultPath() {
return `defaults/a/${BProvider.getThing()}`;
}
}
module.exports = AProvider;b.provider.js与a.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',而不是存根,而且BProvider对global.stuff.whatever的引用引发了一个错误。
为什么这不管用?
发布于 2017-03-02 12:29:23
关于为什么会发生这种情况的答案如下
proxyquire仍然需要底层代码,然后才能退出它。它这样做是为了启用回调。
解决方案只是显式地不允许调用。
试验结果如下:
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')
});
});
});运行此测试非常有效。
https://stackoverflow.com/questions/42550134
复制相似问题