React Native Testing - 如何在快照之外进行TDD和测试组件?

时间:2017-01-11 07:27:10

标签: reactjs react-native tdd jestjs

我真的在如何测试React Native组件,而不是使用来自jest的快照。这些非常适合根据传递到组件中的某些数据测试某些内容,但似乎没有办法测试事件或事件处理程序,检查事件监听器是否在生命周期方法中正确设置或断开连接等...就像感觉我要么缺少某些东西,要么工具不完整。

同样在旁注中,快照测试在TDD方面感觉倒退,因为只有在获得应用程序代码后才能编写测试...对此有何看法?

2 个答案:

答案 0 :(得分:0)

使用快照测试,您只能检查道具和样式等中的值。要检查容器中的某些逻辑,我使用了浅层'来自酶;)

答案 1 :(得分:0)

您仍然可以将快照与事件结合使用,例如:点击按钮并在点击后验证渲染的输出:

it('should render Markdown in preview mode', () => {
  const wrapper = shallow(
    <MarkdownEditor value="*Hello* Jest!" />
  );

  expect(wrapper).toMatchSnapshot();

  wrapper.find('[name="toggle-preview"]').simulate('click');

  expect(wrapper).toMatchSnapshot();
});

要测试该事件处理程序被称为属性,您可以执行以下操作:

it('should pass a selected value to the onChange handler', () => {
  const value = '2';
  const onChange = jest.fn();
  const wrapper = shallow(
    <Select items={ITEMS} onChange={onChange} />
  );

  expect(wrapper).toMatchSnapshot();

  wrapper.find('select').simulate('change', {
    target: { value },
  });

  expect(onChange).toBeCalledWith(value);
});

(这两个例子来自我在testing React components with Jest上的文章。)

相关问题