首页 文章

Enzyme / React浅层渲染是否昂贵?

提问于
浏览
4

我们正在讨论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中,每个测试都有一个新的浅包装器,基本上什么都没有改变但是有道具 .

在100次测试过程中,您认为完成时间的差异是什么?

也有可能在较高范围内浅一次渲染(测试A)会污染测试状态吗?

2 回答

  • 3

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

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

  • 1

    shallow 可能不是你的问题,因为它是_2603253的儿童渲染 .

    您可以考虑更改测试运行引擎然后,例如,与Jest相比,AVA有点慢 . 我在一年前做了这个改变,而且速度快了很多 . Jest还在其基础套件中提供了更多有用的东西,例如模拟函数的例子 .

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

相关问题