Sac*_*in 16 typescript reactjs enzyme
任何人都可以帮我测试酶中的input.focus().我正在用react.My代码编写脚本.
public inputBox: any;
componentDidUpdate = () => {
setTimeout(() => {
this.inputBox.focus();
}, 200);
}
render() {
return (
<div>
<input
type = 'number'
ref = {element => this.inputBox = element } />
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
小智 20
你可以使用mount
而不是浅.然后你可以比较document.activeElement
和输入DOM节点的相等性.
const output = mount(<MyFocusingComponent/>);
assert(output.find('input').node === document.activeElement);
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅https://github.com/airbnb/enzyme/issues/316.
Per React 16.3更新... createRef
如果你重新安排原始组件使用新的ref api,今天访问此帖子的任何人都可以使用
class InputBox extends PureComponent {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentDidMount() {
this.inputRef.current.focus();
}
render() {
return (
<input
ref={this.inputRef}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的测试规范中
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);
});
Run Code Online (Sandbox Code Playgroud)
请注意使用inputRef.current
引用当前分配的DOM节点的属性.
其他方法是测试元素增益是否集中,即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);
Run Code Online (Sandbox Code Playgroud)
这个例子使用了Jasmine的spyOn,尽管你可以使用任何你喜欢的间谍.