2016-08-02 42 views
48

在发布这个问题之前,我试图在sqa stackexchange中搜索,但是我没有发现关于浅度和渲染的帖子,所以我希望有人能帮助我。什么时候应该在酶/反应测试中使用渲染和浅层?

什么时候应该使用浅层渲染测试反应组件? 基础上制作的Airbnb文档,我做了一些意见上的两个的区别:

  1. 由于浅正在测试组件为单位,所以它应该用于“父”组件。 (例如表格,包装等)

  2. 渲染是针对子组件的。

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

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

回答

83

按照酶学docs

mount(<Component />)的全部DOM渲染是理想的,你有可能与DOM API的交互,或者可能需要以完全测试组件的整个生命周期的组件使用情况(即,componentDidMount等)

shallow(<Component />)浅层渲染是有用的给自己限制在测试一个组件作为一个单元,并确保您的测试不是间接断言在子组件的行为。

render其用于呈现反应的组分,以静态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)); 
}); 

注意渲染,设置道具找到选择器甚至合成事件都支持浅渲染,所以大多数时候你可以使用它。

但是,您将无法获得组件的完整生命周期,因此如果您期望发生在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); 
}); 

希望这有助于!

+1

明确的解释人! –

+1

我还没有得到100%,为什么三个动词带来不同的方法。例如,可以在浅层使用wrapper.getNode(),但不能在渲染中使用。任何解释/链接/文档/博客,可以帮助我解决这个问题? – Paulquappe

+0

什么是更高性能? “渲染”还是“浅”? –

相关问题