【问题标题】:Are Enzyme / React shallow renders expensive?Enzyme / React 浅渲染是否昂贵?
【发布时间】:2016-08-03 16:29:47
【问题描述】:

我们正在讨论 Enzyme shallow renders 以及每次测试在每次测试中重新运行浅层的时间。无论是方法、点击次数、选择器长度等,我建议我们的测试可能会运行得更快,如果我们在测试运行前 一次对组件进行浅层渲染,而不是 每个时间。

有没有专家可以指出哪种方式更快,以及哪种方式存在任何陷阱?这些示例使用了AVA runner(为了讨论而稍微做作)。

例如,这是一种方式 (A)...

import TagBox from '../TagBox';
const props = { toggleValue: sinon.spy() };
let wrapper = {};

test.before(t => {
    wrapper = shallow(<TagBox />);
});

test('it should have two children', t => {
    t.is(wrapper.children().length, 2);
});

test('it should safely set props', t => {
    wrapper.setProps({...props});
    t.is(wrapper.children().length, 2);
});

test('it should call when clicked', t => {
    wrapper.setProps({...props});
    wrapper.find({tagX : true}).last().simulate('click');
    t.true(props.toggleValue.calledOnce);
});

这是另一个(B)...

import TagBox from '../TagBox';

test('it sets value to null ...', t => {
    const props = {multiple: false};
    const wrapper = shallow(<TagBox {...props} />);
    t.is(wrapper.state('currentValue'), null);
});

test('it sets value to [] if multiple', t => {
    const props = {multiple: true};
    const wrapper = shallow(<TagBox {...props} />);
    t.deepEqual(wrapper.state('currentValue'), []);
});

test('it does not use value if ...', t => {
    const props = = {value: 3};
    const wrapper = shallow(<TagBox {...props} />);
    t.is(wrapper.state('currentValue'), null);
});

// etc. etc.

请注意,在测试 B 中,每个测试都有一个新的浅层包装器,而实际上除了 props 没有任何变化。

在 100 次测试过程中,您预计完成时间的差异是多少?

还有没有机会在更高的范围内进行一次浅渲染(测试 A)会污染测试状态?

【问题讨论】:

    标签: reactjs enzyme ava


    【解决方案1】:

    Shallow 渲染器的设计速度很快,因为它只渲染单个组件。因此,当您为每个测试创建新组件时,通常不会遇到任何性能问题。

    此外,如果 TagBox 组件具有内部状态,您的示例 A 可能无法正常工作。这就是为什么示例 B 是编写测试的更可取的方式。

    【讨论】:

      【解决方案2】:

      shallow 在这里可能不是您的问题,因为它被设计为渲染组件的最快方式,而无需级联所有子渲染。

      那么您可以考虑更改您的测试运行引擎,例如,与 Jest 相比,AVA 有点慢。一年前我做了这个改变,它快了很多。 Jest 还在它的基本套件中提供了更多有用的东西,例如模拟函数。

      更多:https://facebook.github.io/jest/

      【讨论】:

        猜你喜欢
        • 2017-03-11
        • 2016-12-18
        • 2018-04-28
        • 2016-10-29
        • 1970-01-01
        • 2020-03-12
        • 1970-01-01
        • 2020-08-15
        • 2019-03-19
        相关资源
        最近更新 更多