Javascript 测试「;焦点“;输入上的元素在vue测试库中不工作
我有一个Vue组件(模态),如果挂载上有一个活动元素,它会从活动元素中移除焦点,如果有Javascript 测试「;焦点“;输入上的元素在vue测试库中不工作,javascript,vue.js,jestjs,testing-library,Javascript,Vue.js,Jestjs,Testing Library,我有一个Vue组件(模态),如果挂载上有一个活动元素,它会从活动元素中移除焦点,如果有输入元素,则聚焦它找到的第一个输入。代码正在运行,我对第一个案例进行了运行测试 我的测试评估了一个输入元素是否被关注,但并没有起作用,我也找不到我的错误 vue组件的相关代码部分: mounted() { this.removeActiveFocusedElements() if (this.autoFocusFirstInputElement) { this.focusFirs
输入
元素,则聚焦它找到的第一个输入。代码正在运行,我对第一个案例进行了运行测试
我的测试评估了一个输入元素是否被关注,但并没有起作用,我也找不到我的错误
vue组件的相关代码部分:
mounted() {
this.removeActiveFocusedElements()
if (this.autoFocusFirstInputElement) {
this.focusFirstInput()
}
}
removeActiveFocusedElements() {
if (document.activeElement) {
document.activeElement.blur()
}
}
focusFirstInput() {
const firstInput = this.$el.querySelector('input')
if (firstInput) {
firstInput.focus()
}
}
相关测试部分:
const wrapper = document.createElement('div')
const initialFocusedElement = document.createElement('button')
wrapper.appendChild(initialFocusedElement)
initialFocusedElement.setAttribute('data-testid', 'initial-focused-element')
const container = render(Modal, {
container: document.body.appendChild(wrapper),
slots: {
header: '<h2>Dialog</h2>',
body: '<div><input type="text" data-testid="first-input"/></div>'
}
})
const firstInput = container.getByTestId('first-input')
expect(firstInput).toHaveFocus()
expect(document.body).not.toHaveFocus()
const wrapper=document.createElement('div')
const initialFocusedElement=document.createElement('按钮')
appendChild(initialFocusedElement)
setAttribute('data-testid','initial-focusedelement')
常量容器=渲染(模式{
容器:document.body.appendChild(包装器),
插槽:{
标题:“对话框”,
正文:“”
}
})
const firstInput=container.getByTestId('first-input')
expect(firstInput).toHaveFocus()
expect(document.body).not.toHaveFocus()
我知道/尝试过的事情:
- 如果我没有输入元素并从vue组件中删除
,则会聚焦removeActiveFocusedElements()
,因此这是可行的,我对此进行了测试initialFocusedElement
位于“DOM”中- 调用focusFirstInput()并查找输入元素
- 如果我在
之后记录firstInput.focus()
,它就是带有测试id的输入元素,因此它是正确的document.activeElement.outerHTML
- 但是,如果我在测试中记录document.activeElement.outerHTML,它就是主体,所以我的预期当然失败了
- 我用
试过了,没有任何区别queryByTestId