在Enzyme中测试input.focus()

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.


Pra*_*cer 9

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节点的属性.


mck*_*omo 7

其他方法是测试元素增益是否集中,即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,尽管你可以使用任何你喜欢的间谍.

  • 将“expect”包装在“setTimeout”中是危险的,因为您的测试运行程序(在我的例子中是 Jest)可能会说测试已经通过,无论“setTimeout”内部发生了什么。通过在“.toHaveBeenCalled”前面放置一个“.not”来尝试一下。 (4认同)
  • `eventStub()` 是从哪里来的? (2认同)