outwest.dev

VueTestingVue Test UtilsVitest

Writing Unit Tests with Vue Test Utils and Vitest (Part 2)

· Updated · 11 min read

This is Part 2 of our series on TheAccordion. If you haven't seen Part 1 please start there.

In this post, we're focusing on unit testing our TheAccordion component using Vitest and Vue Test Utils. We'll walk through setting up a test file and writing tests for rendering, behavior, keyboard navigation and accessibility.

Setting Up The Test File

First, let's create a file named TheAccordion.spec.js. We'll start by importing Vitest, h from Vue, mount from Vue Test Utils, and then our component.

TheAccordion.spec.js
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { h } from 'vue'
import { mount } from '@vue/test-utils'

import TheAccordion from '../TheAccordion.vue'

You may have seen shallowMount recommended for unit tests. Shallow mounting replaces child components with stubs, which helps when a component renders a large tree you don't want to test. Our accordion has no child components, so shallowMount would render exactly the same thing. We'll use mount, which is the simpler default.

Setting up defaults

const defaultProps = () => ({
  sections: [
    { slug: 's1', heading: 'Section 1', content: 'Content 1' },
    { slug: 's2', heading: 'Section 2', content: 'Content 2' },
    { slug: 's3', heading: 'Section 3', content: 'Content 3' },
  ],
});

By setting up our defaultProps as a function that returns an object, we will create a fresh copy of the props for each test. This allows test cases to modify a new object when necessary to test how the component behaves for different props.

So now let's define our suite and set up a reusable render method that we can use.

describe('TheAccordion', () => {
  let wrapper;

  const render = (props = {}) => {
    wrapper?.unmount();
    wrapper = mount(TheAccordion, {
      attachTo: document.body,
      props: { ...defaultProps(), ...props },
    });
  }

  beforeEach(() => {
    render();
  });

  afterEach(() => {
    wrapper.unmount();
    wrapper = null;
  });
});

As you can see, we've now set up our suite of tests called TheAccordion. All of our other tests will be children of this initial suite set up by the describe method.

Let's talk about the render method. It mounts the component and stores the wrapper. It takes a single parameter that's an object, which callers can use to override the default props.

Notice the use of the attachTo property. Our keyboard tests check document.activeElement, and an element can only receive focus if it's actually in the document. Because we attach to the real document.body, we also need to clean up: afterEach unmounts the wrapper, and render unmounts any previous one, for tests that call it again with different props. Without that, every test would leave another accordion in the page for the next test to find.

We then leverage beforeEach so we don't have to call render() within each test.

Render Testing

Now that we have the base of our test file set up, let's write the first batch of tests. We will leverage describe again and build a nested suite of render tests. The rendering suite checks that the component outputs the right elements for the props it's given.

describe('TheAccordion', () => {
  let wrapper;

  // ... render, beforeEach and afterEach

  describe('Rendering', () => {
    it('renders properly', () => {
      const group = wrapper.find('[data-test-id="accordion-group"]');
      const sections = wrapper.findAll('.accordion');

      expect(group.exists()).toBe(true);
      expect(sections.length).toBe(3);
    })

    it('should have the correct number of panels', () => {
      const panels = wrapper.findAll('.accordion-panel');
      expect(panels.length).toBe(3);
    })

    it('should have the correct number of buttons', () => {
      const buttons = wrapper.findAll('.accordion-button');
      expect(buttons.length).toBe(3);
    })

    it('should render the correct heading element', () => {
      render({ headingAs: 'h2' });

      const headings = wrapper.findAll('h2');
      expect(headings.length).toBe(3);
    })

    it('should render with an initial opened section', () => {
      render({ initialOpen: 's2' });

      const panels = wrapper.findAll('.accordion-panel');
      expect(panels.at(1).isVisible()).toBe(true);
    });
  });
});

The tests we've just included should encompass all the rendering states of our component. Because the component sets the open panel from initialOpen during setup, the panel is already open on the first render, and we can check it right away without waiting for the DOM to update.

You can also see how we can override default props by using the render method we set up earlier.

Behavior Testing

Let's start testing the behavior of our component now. When we first start writing tests, it can be hard to know what to test. A good rule to go by is that we want to test the external behavior of the component, not the internal implementation.

This means in the following tests events are triggered, and the test will verify that the actions are handled properly. We don't want to call internal methods directly like togglePanel. If the method name gets changed, or the params change, it could break our tests. This rule paid off here: when the component was rewritten to drop its focus tracking, these tests only needed pointerup changed to click.

In the test below, you'll observe multiple nested describe blocks. This organizational structure enhances the clarity and organization of our test output, making it easier to understand and debug.

// ... render tests and previous code

describe('Behavior', () => {
  let panel;
  let button;

  beforeEach(() => {
    panel = wrapper.find('.accordion-panel');
    button = wrapper.find('.accordion-button');
  })

  describe('Mouse Interactions', () => {
    it('should show the panel when a button is clicked', async () => {
      expect(panel.isVisible()).toBe(false);

      await button.trigger('click');

      expect(panel.isVisible()).toBe(true);
    })

    it('should close an opened panel when their respective button is clicked', async () => {
      await button.trigger('click');

      expect(panel.isVisible()).toBe(true);

      await button.trigger('click');

      expect(panel.isVisible()).toBe(false);
    })

    it('should only have one panel open at a time', async () => {
      const buttons = wrapper.findAll('.accordion-button');
      const panels = wrapper.findAll('.accordion-panel');

      await buttons.at(0).trigger('click');
      await buttons.at(1).trigger('click');

      expect(panels.at(0).isVisible()).toBe(false);
      expect(panels.at(1).isVisible()).toBe(true);
    })
  })

  describe('Keyboard Navigation', () => {
    it('should use native buttons, so Enter and Space work without extra code', () => {
      expect(button.element.tagName).toBe('BUTTON');
      expect(button.attributes('type')).toBe('button');
    })

    describe('Focus Movement', () => {
      it('should move focus to the last button when "End" is pressed', async () => {
        const lastButton = wrapper.findAll('.accordion-button').at(2);

        await button.trigger('keydown', { key: 'End' });

        expect(lastButton.element).toBe(document.activeElement);
      })

      it('should move focus to the first button when "Home" is pressed', async () => {
        const lastButton = wrapper.findAll('.accordion-button').at(2);

        await lastButton.trigger('keydown', { key: 'Home' });

        expect(button.element).toBe(document.activeElement);
      })

      it('should move focus to the next button when "ArrowDown" is pressed', async () => {
        const secondButton = wrapper.findAll('.accordion-button').at(1);

        await button.trigger('keydown', { key: 'ArrowDown' });

        expect(secondButton.element).toBe(document.activeElement);
      })

      it('should move focus to the previous button when "ArrowUp" is pressed', async () => {
        const secondButton = wrapper.findAll('.accordion-button').at(1);

        await secondButton.trigger('keydown', { key: 'ArrowUp' });

        expect(button.element).toBe(document.activeElement);
      })

      it('should wrap from the last button to the first on "ArrowDown"', async () => {
        const lastButton = wrapper.findAll('.accordion-button').at(2);

        await lastButton.trigger('keydown', { key: 'ArrowDown' });

        expect(button.element).toBe(document.activeElement);
      })

      it('should wrap from the first button to the last on "ArrowUp"', async () => {
        const lastButton = wrapper.findAll('.accordion-button').at(2);

        await button.trigger('keydown', { key: 'ArrowUp' });

        expect(lastButton.element).toBe(document.activeElement);
      })
    })
  })
});

Note the use of click and keydown events in the previous tests to match the events we are binding to within the component.

You might notice there's no test that presses Enter or Space and expects a panel to open. The component doesn't handle those keys itself: the browser turns them into a click on any native <button>. jsdom, the browser simulation Vitest runs in, doesn't do that conversion, so the test would fail even though the component works. What our code is responsible for is rendering a real <button type="button">, so that's what we test.

A11y Testing

Finally, we need to ensure that the ARIA attributes are being properly set and contain the correct values. This ensures our component adheres to accessibility standards and provides an inclusive user experience.

// ... all our previous tests - we are nested within the behavior suite of tests

  describe('a11y', () => {
    it('should have the correct aria attributes', () => {
      expect(button.attributes('aria-expanded')).toBe('false');
      expect(panel.attributes('hidden')).toBeDefined();
    })

    it('should update the aria attributes when the panel is shown', async () => {
      await button.trigger('click');

      expect(button.attributes('aria-expanded')).toBe('true');
      expect(panel.attributes('hidden')).not.toBeDefined();
    })

    it('should link each button and panel to each other', () => {
      expect(button.attributes('aria-controls')).toBe(panel.attributes('id'));
      expect(panel.attributes('aria-labelledby')).toBe(button.attributes('id'));
    })

    it('should give each accordion on the page unique ids', () => {
      // useId() is unique per app, so mount both in one parent like a real page.
      const page = mount({
        render: () => [h(TheAccordion, defaultProps()), h(TheAccordion, defaultProps())],
      });
      const [first, second] = page.findAll('.accordion-button');

      expect(first.attributes('id')).not.toBe(second.attributes('id'));

      page.unmount();
    })
  })

The last test needs a little explaining. Vue's useId guarantees unique ids within one app, and each call to mount creates a new app. Two separate mount calls would both get the same first id, so we mount one parent that renders two accordions, the way they'd appear together on a real page.

Conclusion

With the completion of our test suite for the component, it's time to put it to the test. Let's run the suite and verify that all our tests pass without any issues!

 ✓ src/__tests__/TheAccordion.spec.js (19 tests)

 Test Files  1 passed (1)
      Tests  19 passed (19)

These tests check the structure and attributes our component is responsible for. If you want to go further, two things are worth adding:

  • Query by role instead of class. Testing Library can find elements the way assistive technology does, such as "the button named Section 1". If someone breaks the accessible name or role, those tests fail, which class selectors would never catch.
  • Run an automated accessibility check. vitest-axe runs the axe rule set against the rendered component and catches problems we didn't think to write tests for.

This wraps up the unit testing for TheAccordion component, and should provide a good base for setting up tests with Vitest and Vue Test Utils.

View Repo With Source