React TestUtils 模拟焦点
React TestUtils Simulate focus
我正在尝试专注于我的自定义 React 组件之一进行测试。
它 returns 一个带有 onFocus
处理程序的 Input
React 组件。
这是我的测试:
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)
当我使用 const input = TestUtils.scryRenderedDOMComponentsWithTag(myInput, 'div')
在非 React 组件上进行这些精确调用时,一切都按预期进行。我传递给组件的 focusHandler 方法被调用并且测试通过。出于某种原因,我无法让它专注于我的 React 组件。
有人知道这里会发生什么吗?我很困惑。
我发现了问题。我没有在自定义 MyInput
组件 class 中明确处理 type
。我通常只是在创建 MyInput
时将其作为 prop 传递,如下所示:<MyInput type='text' ... />
,但我不小心将其排除在测试之外。
所以测试找不到组件,因为它不知道应该呈现哪种 Input
类型。
我正在尝试专注于我的自定义 React 组件之一进行测试。
它 returns 一个带有 onFocus
处理程序的 Input
React 组件。
这是我的测试:
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)
当我使用 const input = TestUtils.scryRenderedDOMComponentsWithTag(myInput, 'div')
在非 React 组件上进行这些精确调用时,一切都按预期进行。我传递给组件的 focusHandler 方法被调用并且测试通过。出于某种原因,我无法让它专注于我的 React 组件。
有人知道这里会发生什么吗?我很困惑。
我发现了问题。我没有在自定义 MyInput
组件 class 中明确处理 type
。我通常只是在创建 MyInput
时将其作为 prop 传递,如下所示:<MyInput type='text' ... />
,但我不小心将其排除在测试之外。
所以测试找不到组件,因为它不知道应该呈现哪种 Input
类型。