Testing input.focus() in Enzyme

Sachin  picture Sachin · Jun 8, 2016 · Viewed 26k times · Source

Can anyone help me to 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>
    );
}

Answer

whatknight picture whatknight · Jul 15, 2016

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.