Proxyquire doesn't crop my required class

I have an AProvider class that requires './b.provider' .

 const BProvider = require('./b.provider'); class AProvider { static get defaultPath() { return `defaults/a/${BProvider.getThing()}`; } } module.exports = AProvider; 

b.provider.js is next to a.provider.js and looks like

 global.stuff.whatever = require('../models').get('Whatever'); // I didn't write this! class BProvider { static getThing() { return 'some-computed-thing'; } } module.exports = BProvider; 

In my test, I use proxyquire to extract ./b.provider as follows:

 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') }); }); }); 

However, when I run the BProvider test, the actual './b.provider' still required, and not the stub and BProvider reference to global.stuff.whatever gives an error.

Why is this not working?

+5
source share
1 answer

The answer to the question why this happens is as follows

proxyquire still requires basic code before it completes. He does this to allow callsigns.

The solution simply explicitly prohibits calls.

The test will look like this:

 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') }); }); }); 

Doing this test works great.

+4
source

Source: https://habr.com/ru/post/1264927/


All Articles