How do I test input.focus()
in enzyme. I am writing the script with react. My code is below:
public inputBox: any; componentDidUpdate = () => { setTimeout(() => { this.inputBox.focus(); }, 200); } render() { return ( <div> <input type = 'number' ref = {element => this.inputBox = element } /> </div> ); }
To check if an element is focused in React: Set the ref prop on the element. After the element is rendered, check if the element is the active element in the document. If it is, the element is focused.
If you add React to an existing application and render a component into a detached element, React will call focus() before the browser is ready, and the input will not be focused when it gets added to the DOM. So, instead of depending on React to call focus() on the input, we are going to do it ourselves.
You can use mount
instead of shallow. Then you can compare document.activeElement
and the input DOM node for equality.
const output = mount(<MyFocusingComponent/>); assert(output.find('input').node === document.activeElement);
See https://github.com/airbnb/enzyme/issues/316 for more details.
Per React 16.3 updates... using createRef
for anyone visiting this post today, if you rearrange the original component to use the new 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} /> ); } }
Then in your test spec
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); });
Notice the use of the inputRef.current
attribute which references the currently assigned DOM node.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With