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?