Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Stub webpack's require.ensure?

I use webpack's code splitting feature (require.ensure) to reduce the initial bundle size of my React application by loading components that are not visible on page load from a separate bundle that is loaded asynchronously.

This works perfectly, but I have trouble writing a unit test for it.

My test setup is based on Mocha, Chai and Sinon.

Here is the relevant excerpt from the code I have tried so far:

describe('When I render the component', () => {
    let component,
        mySandbox;
    beforeEach(() => {
        mySandbox = sandbox.create();
        mySandbox.stub(require, 'ensure');
        component = mount(<PageHeader />);
    });
    describe('the rendered component', () =>
        it('contains the SideNav component', () =>
            component.find(SideNav).should.have.length(1)
        )
    );
    afterEach(() => mySandbox.restore());
});

When running the test, I get this error message:

"before each" hook for "contains the SideNav component": Cannot stub non-existent own property ensure

This happens because require.ensure is a method that only exists in a webpack bundle, but I'm not bundling my tests with webpack, nor do I want to, because it would create more overhead and presumably longer test execution times.

So my question is:

Is there a way to stub webpack's require.ensure with Sinon without running the tests through webpack?

like image 212
Patrick Hund Avatar asked May 22 '17 13:05

Patrick Hund


1 Answers

Each module has its own instance of require so the only way to mock require.ensure is to have some kind of abstraction around require to get this unique require from the required module in test and then add a mock of ensure() to that require instance.

You could use babel-plugin-rewire and use getter to get require, like

const require = myComponent.__get__('require');
require.ensure = () => { /* mock here */};

I'm not 100% sure that it will work but definitely I would try to go in this direction. I recommend reading this issue on github which is related to your problem and explains a lot.

like image 198
Dawid Karabin Avatar answered Oct 18 '22 01:10

Dawid Karabin