首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在酶中检测input.focus()

在酶中检测input.focus()
EN

Stack Overflow用户
提问于 2016-06-08 06:34:24
回答 8查看 42.7K关注 0票数 24

如何在酶中检测input.focus()。我在用反应来写剧本。我的代码如下:

代码语言:javascript
复制
public inputBox: any;

componentDidUpdate = () => {
    setTimeout(() => {
        this.inputBox.focus();
    }, 200);
}

render() {
    return (
        <div>
            <input
                type = 'number'
                ref = {element => this.inputBox = element } />
        </div>
    );
}
EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2017-03-14 14:10:12

另一种方法是测试元素是否获得焦点,即在节点元素上调用focus()。为了实现这一点,需要像在示例中那样通过ref标记引用聚焦元素--将引用分配给this.inputBox。考虑下面的例子:

代码语言:javascript
复制
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);

这个例子使用茉莉花的spyOn,尽管你可以使用任何你喜欢的间谍。

票数 10
EN

Stack Overflow用户

发布于 2016-07-15 19:44:21

您可以使用mount而不是浅层。然后,您可以比较document.activeElement和输入DOM节点是否相等。

代码语言:javascript
复制
const output = mount(<MyFocusingComponent/>);

assert(output.find('input').node === document.activeElement);

有关更多详细信息,请参阅https://github.com/airbnb/enzyme/issues/316

票数 23
EN

Stack Overflow用户

发布于 2018-04-06 18:05:21

响应16.3更新..。如果您重新安排原始组件以使用新的ref api,则今天访问此帖子的任何人都可以使用createRef

代码语言:javascript
复制
class InputBox extends PureComponent {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef();
    }
    componentDidMount() {
        this.inputRef.current.focus();
    }
    render() {
        return (
            <input
                ref={this.inputRef}
            />
        );
    }
}

然后在你的测试规范中

代码语言:javascript
复制
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);
});

注意inputRef.current属性的使用,它引用当前分配的DOM节点。

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37694900

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档