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

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

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

  1. 因为肤浅是测试组件 作为一个整体,所以它应该用于“父”组件(例如,表、包装器等)

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

我之所以问这个问题,是因为我不知道该用哪一种(尽管医生说它们非常相似)

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

92478 次浏览

根据 医生酶:

用于 Full DOM 呈现的 mount(<Component />)非常适合那些组件可能与 DOM apis 交互,或者可能需要完整的生命周期来完全测试组件的用例(例如,Component entDidMount 等)

对。

用于浅层呈现的 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));
});

请注意,渲染布景道具寻找选择器,甚至 合成事件都支持浅显渲染,因此大多数情况下可以直接使用浅显渲染。

但是,您不能获得组件的完整生命周期,因此如果您期望在 Component entDidMount 中发生某些事情,那么您应该使用 mount(<Component />);

这个测试使用 西农来监视组件的 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);
});

希望这个能帮上忙!

浅()和 mount ()之间的区别在于 在 mount ()进行更深入的测试并测试组件的子组件的同时,肤浅()从它们呈现的子组件隔离地测试组件。

这意味着,如果父组件呈现另一个未能呈现的组件,那么父组件上的浅()呈现仍将通过。