我正在使用Jest v16.0.1,react-test-renderer v15.4.0和react-addons-test-utils v15.4.0测试React组件.
该组件已呈现一个按钮:
<button
type="button"
className="btn btn-lg btn-primary btn-danger"
disabled={this.state.cancelButtonDisabled}
onClick={() => this.handleCancel()}
ref="cancelButton"
>Cancel</button>);
Run Code Online (Sandbox Code Playgroud)
在我的测试中,我正在渲染组件:
const component = renderer.create(
<MyComponent />
);
const instance = component.getInstance();
// This works but is ugly
component.toJSON().children[1].children[0].props.onClick();
// This doesn't work
ReactTestUtils.Simulate.click(instance.refs.cancelButton);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
Run Code Online (Sandbox Code Playgroud)
模拟点击此按钮的推荐方法是什么?您可以遍历组件的JSON表示,但看起来它们应该是更好的方法.
在我使用ReactTestUtils.renderIntoDocument之前,您可以使用refs将组件的引用传递给ReactTestUtils.Simulate.click
我已经看到了这个问题 - 如何与ReactTestRenderer/Jest呈现的组件进行交互,但我认为API已经改变,因为我的组件实例没有find()方法.
小智 11
我找到了解决方案.由于您正在使用react,我假设onClick处理函数作为props的一部分传递给按钮.所以你可以通过按钮的道具来访问它.
component.root.findByType('button').props.onClick();
Run Code Online (Sandbox Code Playgroud)
或者,如果您有多个按钮,则可以执行以下操作:
component.root.findByProps({className="btn btn-lg btn-primary btn-danger"}).props.onClick();
Run Code Online (Sandbox Code Playgroud)
dai*_*iki -1
也许为时已晚,但它find是酶的 API。您提到的假设酶问题的答案是按照评论中提到的使用的。
像这样的东西应该有效。
我的组件.jsx
import React from 'react';
class MyComponent extends React.Component {
constructor() {
super();
this.state = {
cancelButtonDisabled: false,
};
}
handleCancel() {
this.props.cancelAction();
}
render() {
return (
<button
type="button"
className="btn btn-lg btn-primary btn-danger"
disabled={this.state.cancelButtonDisabled}
onClick={() => this.handleCancel()}
ref="cancelButton"
>
Cancel
</button>
);
}
}
export default MyComponent;
Run Code Online (Sandbox Code Playgroud)
MyComponent.test.jsx
import React from 'react';
import {mount} from 'enzyme';
import MyComponent from './MyComponent';
describe('Test MyComponent', () => {
it('should be able to click the button', () => {
const mockFunction = jest.fn();
const element = mount(<MyComponent cancelAction={mockFunction} />);
element.find('button').simulate('click');
expect(mockFunction).toHaveBeenCalled();
});
});
Run Code Online (Sandbox Code Playgroud)
如果没有酶,它就会是这样的。
MyComponentWithoutEnzyme.test.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-addons-test-utils';
import MyComponent from './MyComponent';
describe('Test MyComponent', () => {
it('should be able to click the button', () => {
const mockFunction = jest.fn();
const element = ReactTestUtils.renderIntoDocument(
<MyComponent cancelAction={mockFunction} />,
);
const button = ReactDOM.findDOMNode(element);
ReactTestUtils.Simulate.click(button);
expect(mockFunction).toHaveBeenCalled();
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9279 次 |
| 最近记录: |