Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing input.focus() in Enzyme

Tags:

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>     ); } 
like image 945
Sachin Avatar asked Jun 08 '16 06:06

Sachin


People also ask

How do you know if input is focus React?

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.

How do you focus input in functional component?

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.


2 Answers

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.

like image 166
whatknight Avatar answered Dec 11 '22 04:12

whatknight


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.

like image 24
Prancer Avatar answered Dec 11 '22 04:12

Prancer