15

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.

brass monkey
  • 5,841
  • 10
  • 36
  • 61
Constantin Chirila
  • 1,979
  • 2
  • 19
  • 33

1 Answers1

32

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

and try this:

let input = wrapper.find('input').element
expect(input).toBe(document.activeElement);
pranavjindal999
  • 2,937
  • 2
  • 26
  • 35
  • 5
    `attachToDocument` is being deprecated. vue-test-utils docs recommend using `attachTo` instead: [Link to doc](https://vue-test-utils.vuejs.org/api/options.html#attachtodocument) – Nicholas Weber Aug 21 '20 at 17:38
  • 1
    Thanks, this is how to attachTo document body `attachTo: document.body` – Windo Mar 18 '21 at 15:50
  • tip: if you're testing something that focuses on render, remember to call `await nextTick()` before the `expect`. – GuiMendel Aug 12 '23 at 18:23