简体   繁体   English

如何将webpack的require.ensure存根?

[英]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. 我使用webpack的代码拆分功能( require.ensure )来减少我的React应用程序的初始包大小,方法是从异步加载的单独包中加载页面加载时不可见的组件。

This works perfectly, but I have trouble writing a unit test for it. 这很好用, 我在编写单元测试时遇到了麻烦。

My test setup is based on Mocha , Chai and Sinon . 我的测试设置基于MochaChaiSinon

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 “在每个”钩子之前“包含SideNav组件”:不能存根不存在自己的属性确保

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. 发生这种情况是因为require.ensure是一种仅存在于webpack包中的方法,但我不是将我的测试与webpack捆绑在一起,也不是我想要的,因为它会产生更多的开销,并且可能会延长测试执行时间。

So my question is: 所以我的问题是:

Is there a way to stub webpack's require.ensure with Sinon without running the tests through webpack? 有没有办法在没有通过webpack运行测试的情况下使用Sinon将webpack的require.ensure存根?

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. 每个模块都有它自己的实例都需要这么模拟的唯一途径require.ensure是有某种抽象的周围require得到这个独特require从测试所需要的模块,然后添加的模拟ensure()require实例。

You could use babel-plugin-rewire and use getter to get require , like 你可以使用babel-plugin-rewire并使用getter来获取require ,比如

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. 我建议在github上阅读这个与你的问题有关的问题并解释很多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM