【问题标题】:How can you test if an input is focused with Vue Test utils?如何使用 Vue Test utils 测试输入是否聚焦?
【发布时间】:2019-04-02 04:01:20
【问题描述】:

我有一个专注于输入的指令。我想测试这个指令。唯一的问题是我找不到如何测试输入是否集中

这是我的简单模拟组件

 <template>
  <div v-directive>
    <input/>
  </div>
</template>

这是我的指令:

import Vue from 'vue'

export const focusInput = () => {
  return {
    inserted(el: any) {
      el.getElementsByTagName('input')[0].focus()
    }
  }
}

export default Vue.directive('focus-input', focusInput())

这是我的测试:

import Vue from 'vue'
import { mount , createLocalVue} from '@vue/test-utils'

import FocusInputMock from './mockComponents/FocusInputMock.vue'
import {focusInput} from '@/directives/focusInput';

const localVue = createLocalVue()

localVue.directive('directive',  focusInput())


test('update content after changing state', () => {
  const wrapper = mount(FocusInputMock, {
    localVue
  })
  Vue.nextTick(function () {
    expect(wrapper.find('input')) // I have to expect for this input to be focused
  });
})

有人有什么想法吗?我一直在阅读 Jest 和 Vue utils 文档,但没有成功。

【问题讨论】:

    标签: vue.js jestjs vue-test-utils


    【解决方案1】:

    在安装你的模拟组件时,传递{ attachToDocument: true }

    试试这个:

    let input = wrapper.find('input').element
    expect(input).toBe(document.activeElement);
    

    【讨论】:

    • attachToDocument 已被弃用。 vue-test-utils 文档建议使用 attachTo 代替:Link to doc
    • 谢谢,这是附加到文档正文attachTo: document.body
    猜你喜欢
    • 2018-08-06
    • 2019-10-24
    • 2019-04-17
    • 2018-11-09
    • 2018-09-28
    • 2021-04-03
    • 1970-01-01
    • 2019-07-16
    • 2020-11-25
    相关资源
    最近更新 更多