如何在酶中检测input.focus()。我在用反应来写剧本。我的代码如下:
public inputBox: any;
componentDidUpdate = () => {
setTimeout(() => {
this.inputBox.focus();
}, 200);
}
render() {
return (
<div>
<input
type = 'number'
ref = {element => this.inputBox = element } />
</div>
);
}发布于 2017-03-14 14:10:12
另一种方法是测试元素是否获得焦点,即在节点元素上调用focus()。为了实现这一点,需要像在示例中那样通过ref标记引用聚焦元素--将引用分配给this.inputBox。考虑下面的例子:
const wrapper = mount(<FocusingInput />);
const element = wrapper.instance().inputBox; // This is your input ref
spyOn(element, 'focus');
wrapper.simulate('mouseEnter', eventStub());
setTimeout(() => expect(element.focus).toHaveBeenCalled(), 250);这个例子使用茉莉花的spyOn,尽管你可以使用任何你喜欢的间谍。
发布于 2016-07-15 19:44:21
您可以使用mount而不是浅层。然后,您可以比较document.activeElement和输入DOM节点是否相等。
const output = mount(<MyFocusingComponent/>);
assert(output.find('input').node === document.activeElement);有关更多详细信息,请参阅https://github.com/airbnb/enzyme/issues/316。
发布于 2018-04-06 18:05:21
响应16.3更新..。如果您重新安排原始组件以使用新的ref api,则今天访问此帖子的任何人都可以使用createRef。
class InputBox extends PureComponent {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentDidMount() {
this.inputRef.current.focus();
}
render() {
return (
<input
ref={this.inputRef}
/>
);
}
}然后在你的测试规范中
it("Gives immediate focus on to name field on load", () => {
const wrapper = mount(<InputBox />);
const { inputRef } = wrapper.instance();
jest.spyOn(inputRef.current, "focus");
wrapper.instance().componentDidMount();
expect(inputRef.current.focus).toHaveBeenCalledTimes(1);
});注意inputRef.current属性的使用,它引用当前分配的DOM节点。
https://stackoverflow.com/questions/37694900
复制相似问题