简体   繁体   English

React TestUtils模拟焦点

[英]React TestUtils Simulate focus

I'm trying to test focusing on one of my custom React Components. 我正在尝试将测试重点放在我的自定义React组件之一上。

It returns an Input React component with an onFocus handler. 它返回带有onFocus处理程序的Input React组件。

Here is my test: 这是我的测试:

let hasCalledFocus = false
const myInput = TestUtils.renderIntoDocument(
    <MyInput
        focusHandler={() => {
            console.log('focus')
            hasCalledFocus = true
        }}
        hasFocus={false}
        text=''
    />
)

const input = TestUtils.scryRenderedComponentsWithType(myInput, Input)
expect(hasCalledFocus).to.eql(false)
TestUtils.Simulate.focus(input[0])
expect(hasCalledFocus).to.eql(true)

When I make these exact calls on a non-React component, using const input = TestUtils.scryRenderedDOMComponentsWithTag(myInput, 'div') , everything works as expected. 当我在非反应组件上进行这些精确调用时,使用const input = TestUtils.scryRenderedDOMComponentsWithTag(myInput, 'div') ,一切都会按预期进行。 The focusHandler method I pass to the component is called and the test passes. 我传递给组件的focusHandler方法被调用,测试通过。 For some reason, I can't get it to focus on my React component. 出于某种原因,我无法集中精力于我的React组件。

Anyone have any ideas as to what could be going on here? 有人对这里可能发生的事情有任何想法吗? I'm pretty stumped. 我很沮丧。

I found the issue. 我发现了问题。 I wasn't handling type explicitly in my custom MyInput component class. 我没有在自定义MyInput组件类中显式处理type I am usually just passing it as a prop when I create MyInput , like so: <MyInput type='text' ... /> , but I had left that out of my test by accident. 创建MyInput时,我通常只是通过它作为道具,就像这样: <MyInput type='text' ... /> ,但是我无意中把它排除在了测试之外。

So the test couldn't find the component because it didn't know what kind of Input type it's supposed to render. 因此测试无法找到该组件,因为它不知道应该呈现哪种Input类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM