首页 文章

什么时候应该在酶/反应测试中使用渲染和浅?

提问于
浏览
76

在发布这个问题之前,我试图在sqa stackexchange中搜索,但我发现没有关于浅的帖子并在那里渲染,所以我希望有人可以帮助我 .

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

  • 由于浅是测试组件 as a unit ,所以它应该用于'parent'组件 . (例如 table ,包装等)

  • 渲染用于子组件 .

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

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

2 回答

  • 130

    按照酶docs

    mount(<Component />) for Full DOM渲染非常适用于您拥有可能与DOM apis交互的组件的情况,或者可能需要整个生命周期才能完全测试组件(即componentDidMount等)

    shallow(<Component />) for Shallow渲染对于约束自己将组件作为一个单元进行测试很有用,并确保您的测试不会间接断言子组件的行为 .

    render 用于将响应组件呈现给 static HTML 并分析生成的HTML结构 .

    您仍然可以在浅层渲染中看到基础"nodes",例如,您可以使用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));
    });
    

    请注意,浅渲染支持渲染,设置道具和查找选择器甚至合成事件,因此大多数情况下您可以使用它 .

    但是,您将无法获得组件的整个生命周期,因此如果您希望在componentDidMount中发生事情,则应使用 mount(<Component />) ;

    此测试使用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);
    });
    

    希望这可以帮助!

  • 4

    shallow()和mount()之间的区别在于shallow()测试组件与它们呈现的子组件隔离,而mount()更深入并测试组件的子组件 . 对于shallow(),这意味着如果父组件渲染另一个无法渲染的组件,那么父级上的浅()渲染仍将传递 .

相关问题