javascriptvue.jsvitest

Vue 3 - Testing ref's focus() method


I'm having some issues trying to figure out why my very simple test case keeps failing. I'm trying to learn how testing in Vue works and have very simple test, where element.focus() is trigger onMount(() => /* see implementation 👇*/).

Here is my component:

<script setup>
import { ref, onMounted } from 'vue';

const myInputRef = ref<HTMLInputElement | null>(null);
onMounted(() => {
  if (myInputRef.value) {
    myInputRef.value.focus();
  }
});
</script>

<template>
  <input ref="myInputRef" name="my-input" type="text">
  <label for="my-input">input:</label>
</template>

and my test case:

describe('App', () => {
  it('should auto focus input element', async () => {
    const wrapper = mount(App);
    const inputElement = wrapper.find('input');

    expect(inputElement.exists()).toBeTruthy();
    await nextTick();
    expect(document.activeElement).toBe(inputElement.element);
  });
});

The result is that, expect(inputElement.exists()).toBeTruthy() evaluates fine but expect(document.activeElement).toBe(inputElement.element) results in:

AssertionError: expected <body></body> to be <input name="my-input" …(1)></input> // Object.is equality

enter image description here

What am I not understanding?


Solution

  • Github Issue for enzyme.js (react) document.activeElement

    Here we are discussing the same JavaScript issue, regardless of the framework and package.

    The wrapper needs to be attached to the document body.

    const wrapper = mount(App, { attachTo: document.body });
    

    If you comment out the line myInputRef.value.focus(), you will clearly see that the default value of activeElement is the body, due to the attachTo parameter.