Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 679
Constantin Chirila Avatar asked Oct 29 '18 08:10

Constantin Chirila


People also ask

What is Vue test utils?

Vue Test Utils (VTU) is a set of utility functions aimed to simplify testing Vue. js components. It provides some methods to mount and interact with Vue components in an isolated manner.

What are stubs in Vue test utils?

Vue Test Utils provides some advanced features for stubbing components and directives. A stub is where you replace an existing implementation of a custom component or directive with a dummy one that doesn't do anything at all, which can simplify an otherwise complex test. Let's see an example.

What is e2e testing in Vue?

End-to-end testing is basically a type of testing that mirrors how a user would use the application. The idea is to test the application as a whole, including components like databases, third-party services, analytics, etc. Each test could be written as a user story.


1 Answers

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

and try this:

let input = wrapper.find('input').element
expect(input).toBe(document.activeElement);
like image 141
pranavjindal999 Avatar answered Sep 22 '22 19:09

pranavjindal999