【发布时间】:2017-04-02 23:42:59
【问题描述】:
我正在使用 Jest 和快照测试。我想做的是用ReactTestRenderer 渲染一个组件,然后模拟单击其中的一个按钮,然后验证快照。
ReactTestRenderer 的 create 调用返回的对象有一个 getInstance 函数,允许我直接调用它的方法,但它似乎不适用于 ReactTestUtils 中的任何 find/scry 方法。
我可以手动遍历树并点击按钮,但似乎必须有更好的方法:
import React from 'react';
import ReactDOM from 'react-dom';
import MyCounter from './MyCounter';
import renderer from 'react-test-renderer';
import {Simulate, findRenderedDOMComponentWithClass} from 'react-addons-test-utils';
it('should render 0', () => {
const component = renderer.create(<MyCounter/>);
const inst = component.getInstance();
// Calling methods directly works, but that's not the same as
// simulating a click on the button...
inst.increment();
// This also works, but it's awfully verbose...
component.toJSON().children[1].props.onClick();
// I'm looking for something like...
// inst.find('.increment').click()
// or:
// Simulate.click(inst.find('.increment'))
// or:
// Simulate.click(findRenderedDOMComponentWithClass(inst, 'increment'))
// Finally, verify the snapshot
expect(component.toJSON()).toMatchSnapshot();
});
这样的东西存在吗?
【问题讨论】:
-
您正在寻找的是 Enzyme:airbnb.io/enzyme ...但是 jest 确实需要一个横向快照的工具,因为 Enzyme 引入了更多不必要的东西和潜在的瓶颈。我认为 2017 年的目标只是使用 Jest。当 React 如此可靠时,实际上并不需要模拟点击(通过 DOM)。此外,当快照结合无状态组件如此强大时,您几乎不需要 css 样式选择器。这样就只剩下需要选择器来快速调用用作道具的函数了。现在必须有一个具有基本选择器的库..