Constantin Chirila
Constantin Chirila

Reputation: 2119

How can you test if an input is focused with Vue Test utils?

I have a directive that focuses on the input. And i want to test this directive. The only issue is i can't find how i can test if the input is focused

This is my simple mock component

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

This is my directive:

import Vue from 'vue'

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

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

This is my test:

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
  });
})

Anyone has any ideas? I've been reading the Jest and Vue utils docs without any success.

Upvotes: 17

Views: 13606

Answers (1)

pranavjindal999
pranavjindal999

Reputation: 3047

While mounting your mock component, pass { attachToDocument: true }

and try this:

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

Upvotes: 35

Related Questions