DEV Community

Manish Kumar
Manish Kumar

Posted on

Refactoring Vue 3 Unit Tests: Moving from Mutable beforeEach State to Functional Factory Helpers in TypeScript


When migrating large Vue codebases to TypeScript, static typing often exposes patterns in our test suites that are brittle or unnecessary. One common pattern in older Vue Test Utils specs is storing a mutable let wrapper variable in the test scope and initializing it inside beforeEach().

In my recent contribution to GitLab's Contributors Platform (MR !3204), I converted the Labelathon page's DetailsSection component to TypeScript and refactored its unit test suite to use functional factory helpers.

Here is a look at why this refactoring improves test clarity, type inference, and test isolation.


The Component: DetailsSection.vue

The DetailsSection component renders instructions and event guidelines using accordion components from bootstrap-vue-next alongside a custom MarkdownRenderer:

<script setup lang="ts">
import { BAccordion, BAccordionItem } from 'bootstrap-vue-next';
import MarkdownRenderer from '~/common/components/MarkdownRenderer.vue';
</script>

<template>
  <BAccordion class="mt-4">
    <BAccordionItem title="Rules & Guidelines">
      <MarkdownRenderer :markdown="guidelines" />
    </BAccordionItem>
    <!-- Additional accordion items -->
  </BAccordion>
</template>
Enter fullscreen mode Exit fullscreen mode

Adding lang="ts" ensures strict compilation of imported third-party components and child component props.


The Spec: Mutable beforeEach vs. Pure createWrapper

The Old Pattern (JavaScript)

Previously, the spec relied on an outer mutable reference:

// Before (DetailsSection.spec.js)
describe('DetailsSection', () => {
  let wrapper;

  beforeEach(() => {
    wrapper = shallowMount(DetailsSection, {
      global: {
        renderStubDefaultSlot: true,
      },
    });
  });

  it('contains the expected content', () => {
    expect(wrapper.html()).toMatchSnapshot();
  });
});
Enter fullscreen mode Exit fullscreen mode

Why avoid this pattern in TypeScript?

  1. Unnecessary State Mutation: A global let wrapper introduces shared state across tests. Tests should be isolated and idempotent.
  2. Type Ambiguity: In TypeScript, declaring let wrapper; defaults to any unless explicitly typed (VueWrapper<InstanceType<typeof DetailsSection>>), which adds boilerplate.
  3. Execution Overhead: If some test cases only test static exports or helpers, beforeEach still mounts the component unnecessarily.

The Modern Pattern (TypeScript)

In DetailsSection.spec.ts, we eliminated beforeEach and the mutable variable in favor of a concise factory helper:

// After (DetailsSection.spec.ts)
import { shallowMount } from '@vue/test-utils';
import DetailsSection from './DetailsSection.vue';

describe('DetailsSection', () => {
  const createWrapper = () =>
    shallowMount(DetailsSection, {
      global: {
        renderStubDefaultSlot: true,
      },
    });

  it('contains the expected content', () => {
    expect(createWrapper().html()).toMatchSnapshot();
  });
});
Enter fullscreen mode Exit fullscreen mode

Why this is better:

  • Automatic Type Inference: createWrapper() naturally returns a typed VueWrapper, avoiding manual type annotations.
  • Pure & Self-Contained: Each test explicitly invokes createWrapper() with optional prop overrides when needed, preventing test leakage.
  • Seamless Snapshot Migration: The Vitest snapshot was smoothly renamed from DetailsSection.spec.js.snap to DetailsSection.spec.ts.snap without breaking snapshot verification.

Key Takeaways

  1. Favor Factory Functions over beforeEach: Pure createWrapper = (props = {}) => ... functions result in cleaner, more readable specs compared to mutating a shared let wrapper variable.
  2. Leverage Type Inference in Tests: By using inline factory functions, Vue Test Utils and Vitest automatically infer wrapper types without verbose casting.
  3. Clean Codebases One Slice at a Time: Converting small presentation components and their specs in focused merge requests keeps review cycles fast and eliminates maintenance debt.

Check out the merged Merge Request on GitLab:

👉 GitLab Contributors MR !3204


Author: Manish Kumar

GitLab: @manishpatel00

Top comments (0)