Vue Answers

How to test if an input is focused with Vue Test Utils?

Spread the love

To test if an input is focused using Vue Test Utils, you can use the wrapper.find() method to select the input element and then check its element property to see if it’s focused.

To do this we can write something like

import { mount } from '@vue/test-utils';
import YourComponent from '@/components/YourComponent.vue'; // import your component

describe('YourComponent', () => {
  it('should focus on input when clicked', async () => {
    const wrapper = mount(YourComponent); // mount your component

    // Find the input element
    const input = wrapper.find('input');

    // Simulate a focus event on the input
    await input.trigger('focus');

    // Check if the input is focused
    expect(input.element === document.activeElement).toBe(true);

In this example, mount(YourComponent) mounts your Vue component for testing.

wrapper.find('input') selects the input element within the component.

await input.trigger('focus') simulates a focus event on the input element.

input.element === document.activeElement checks if the input element is currently focused.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *