【问题标题】:When should you use render and shallow in Enzyme / React tests?什么时候应该在 Enzyme / React 测试中使用 render 和 shallow?
【发布时间】:2016-12-07 05:03:04
【问题描述】:

在发布这个问题之前,我尝试在 sqa stackexchange 中搜索,但我没有找到关于浅层和渲染的帖子,所以我希望有人可以在这里帮助我。

什么时候应该在测试 React 组件时使用 shallow 和 render? 根据airbnb的文档,我对两者的区别提出了一些看法:

  1. 由于浅层将组件作为一个单元进行测试,因此它应该用于“父”组件。 (例如表格、包装器等)

  2. 渲染用于子组件。

我问这个问题的原因是我很难弄清楚我应该使用哪一个(尽管文档说它们非常相似)

那么,我如何知道在特定场景中使用哪一个?

【问题讨论】:

  • shallow() 和 mount() 之间的区别在于,shallow() 将组件与它们渲染的子组件隔离开来,而 mount() 更深入并测试组件的子组件。对于 shallow() 这意味着如果父组件渲染了另一个渲染失败的组件,那么在父组件上的 shallow() 渲染仍然会通过。

标签: testing meteor reactjs chai enzyme


【解决方案1】:

根据酶docs:

mount(<Component />) 用于完整 DOM 渲染非常适合您拥有可能与 DOM api 交互的组件或可能需要完整生命周期才能完全测试组件(即 componentDidMount 等)的用例

对比

shallow(<Component />) 用于浅渲染有助于限制您将组件作为一个单元进行测试,并确保您的测试不会间接断言子组件的行为。

对比

render 用于将 React 组件渲染为 静态 HTML 并分析生成的 HTML 结构。

您仍然可以在浅层渲染中看到底层的“节点”,因此,例如,您可以使用 AVA 作为规范运行器来执行以下(稍微做作)示例:

let wrapper = shallow(<TagBox />);

const props = {
    toggleValue: sinon.spy()
};

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

test('it should safely set all props and still render two nodes', t => {
    wrapper.setProps({...props});
    t.is(wrapper.children().length, 2);
});

test('it should call toggleValue when an x class is clicked', t => {
    wrapper.setProps({...props});
    wrapper.find('.x').last().simulate('click');
    t.true(props.toggleValue.calledWith(3));
});

注意 rendering、setting props 和 finding selectors 甚至 synthetic events 都支持浅渲染,所以大多数时候你可以使用它。

但是,您将无法获得组件的完整生命周期,因此如果您希望在 componentDidMount 中发生某些事情,您应该使用mount(&lt;Component /&gt;);

此测试使用Sinon 来监视组件的componentDidMount

test.only('mount calls componentDidMount', t => {

    class Test extends Component {
        constructor (props) {
            super(props);
        }
        componentDidMount() {
            console.log('componentDidMount!');
        }
        render () {
            return (
                <div />
            );
        }
    };

    const componentDidMount = sinon.spy(Test.prototype, 'componentDidMount');
    const wrapper = mount(<Test />);

    t.true(componentDidMount.calledOnce);

    componentDidMount.restore();
});

浅渲染或渲染

以上不会通过

render 只会为您提供 html,因此您仍然可以执行以下操作:

test.only('render works', t => {

    // insert Test component here...

    const rendered = render(<Test />);
    const len = rendered.find('div').length;
    t.is(len, 1);
});

希望这会有所帮助!

【讨论】:

【解决方案2】:

shallow() 和 mount() 之间的区别在于 shallow() 测试组件与它们渲染的子组件隔离,而 mount() 更深入并测试组件的子组件。

对于shallow(),这意味着如果父组件渲染另一个未能渲染的组件,那么在父组件上的shallow() 渲染仍然会通过。

【讨论】:

  • 当我测试props 的组件时,我应该使用shallow 和mount 吗?
猜你喜欢
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 2015-05-19
  • 2023-04-02
  • 2011-04-15
  • 2017-04-10
  • 2012-03-19
  • 2018-05-12
相关资源
最近更新 更多