Beginner's Guide to Vitest: Setting Up Frontend Testing and Core Syntax

Hello, this is Lovefield.

As a frontend codebase grows, a common source of anxiety arises: "If I modify this function, will it accidentally break another page?" Automated testing serves as the most reliable safety net against these regressions.

While Jest was the traditional go-to tool for years, Vitest has quickly become the modern standard for Vite and TypeScript projects. Because it reuses your existing vite.config.ts directly without complex transpilation setups, it offers an exceptionally gentle learning curve for developers writing tests for the first time.

In this guide, we will walk through Vitest from scratch—covering installation, fundamental test syntax, mocking basics, and how to test Vue 3 composables and components.

Installing and Configuring Vitest

If you already have a Vite-based project (Vue, React, or Vanilla TypeScript), adding Vitest takes just a single command using bun:

Shell

1

bun add -d vitest

Adding Scripts to package.json

Add convenient test scripts to your package.json:

JSON

1

2

3

4

5

6

{
  "scripts": {
    "test": "vitest",
    "test:run": "vitest run"
  }
}
  • bun run test: Launches Vitest in Watch Mode, automatically re-running relevant tests whenever you save a file. Ideal during active development.

  • bun run test:run: Runs the entire test suite once and exits. Primarily used in CI/CD deployment pipelines.

Writing Your First Test (Core Syntax)

By default, Vitest automatically detects any file ending in .test.ts or .spec.ts.

Let's create a simple discount calculation utility and write a test suite to verify its behavior.

TypeScript

1

2

3

4

5

6

7

// utils/price.ts
export function calculateDiscount(price: number, discountRate: number): number {
  if (discountRate < 0 || discountRate > 100) {
    throw new Error('Discount rate must be between 0 and 100.');
  }
  return price * (1 - discountRate / 100);
}

Next, create price.spec.ts in the same directory:

TypeScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

// utils/price.spec.ts
import { describe, it, expect } from 'vitest';
import { calculateDiscount } from './price';

// 1. describe: Groups related test cases into a logical suite.
describe('calculateDiscount utility', () => {
  
  // 2. it (or test): Defines an individual test case to verify.
  it('returns 8,000 when a 20% discount is applied to 10,000', () => {
    const result = calculateDiscount(10000, 20);
    
    // 3. expect: Asserts that the actual output matches the expected value.
    expect(result).toBe(8000);
  });

  it('returns the original price when the discount rate is 0%', () => {
    expect(calculateDiscount(5000, 0)).toBe(5000);
  });

  it('throws an error when the discount rate exceeds 100%', () => {
    // Wrap the function call in an arrow function when asserting thrown errors.
    expect(() => calculateDiscount(10000, 120)).toThrow('Discount rate must be between 0 and 100.');
  });
});

Essential Matchers to Know

  • expect(a).toBe(b): Checks strict equality (===) for primitive values like numbers, strings, and booleans.

  • expect(objA).toEqual(objB): Performs deep equality checks for objects and arrays.

  • expect(val).toBeTruthy() / toBeFalsy(): Verifies whether a value evaluates to true or false in a boolean context.

  • expect(arr).toContain(item): Checks whether an array contains a specific item.

Spying on Functions with Mocking (vi.fn())

In real-world applications, you often need to verify whether a callback function was triggered without making actual network requests or side effects. Replacing real dependencies with simulated functions is known as Mocking.

Vitest makes this straightforward with vi.fn():

TypeScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

// utils/logger.spec.ts
import { describe, it, expect, vi } from 'vitest';

function processOrder(amount: number, onSuccess: (msg: string) => void) {
  if (amount > 0) {
    onSuccess(`Payment of $${amount} completed.`);
  }
}

describe('processOrder callback verification', () => {
  it('invokes onSuccess once when the payment amount is greater than 0', () => {
    // Create a mock function
    const mockCallback = vi.fn();

    processOrder(150, mockCallback);

    // Assert call count and passed arguments
    expect(mockCallback).toHaveBeenCalledTimes(1);
    expect(mockCallback).toHaveBeenCalledWith('Payment of $150 completed.');
  });

  it('does not invoke the callback when the amount is 0 or negative', () => {
    const mockCallback = vi.fn();

    processOrder(0, mockCallback);

    expect(mockCallback).not.toHaveBeenCalled();
  });
});

Getting Started with Vue 3 Testing

In a Vue 3 application, it is helpful to divide your tests into two straightforward categories: state logic (Composables) and UI rendering (Components).

Testing a Vue Composable

Pure reactive functions (ref, computed) that do not rely on DOM mounting can be tested directly just like regular TypeScript functions:

TypeScript

1

2

3

4

5

6

7

8

9

10

11

12

13

// composables/useCounter.ts
import { ref, computed } from 'vue';

export function useCounter(initialValue = 0) {
  const count = ref(initialValue);
  const doubleCount = computed(() => count.value * 2);

  const increment = () => {
    count.value++;
  };

  return { count, doubleCount, increment };
}

TypeScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

// composables/useCounter.spec.ts
import { describe, it, expect } from 'vitest';
import { useCounter } from './useCounter';

describe('useCounter', () => {
  it('updates both count and doubleCount when increment is called', () => {
    const { count, doubleCount, increment } = useCounter(1);

    expect(count.value).toBe(1);
    expect(doubleCount.value).toBe(2);

    increment();

    expect(count.value).toBe(2);
    expect(doubleCount.value).toBe(4);
  });
});

Testing Vue Component Rendering and Click Events

To verify that a .vue component renders text properly and responds to user clicks, install @vue/test-utils along with jsdom (a simulated browser DOM environment):

Shell

1

bun add -d @vue/test-utils jsdom

Next, enable environment: 'jsdom' inside your vite.config.ts:

TypeScript

1

2

3

4

5

6

7

8

9

10

// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  plugins: [vue()],
  test: {
    environment: 'jsdom',
  },
});

Now, let's mount a simple button component and simulate a user click:

Vue

1

2

3

4

5

6

7

8

9

10

<!-- components/LikeButton.vue -->
<script setup lang="ts">
import { ref } from 'vue';

const likes = ref(0);
</script>

<template>
  <button @click="likes++">Likes: {{ likes }}</button>
</template>

TypeScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

// components/LikeButton.spec.ts
import { describe, it, expect } from 'vitest';
import { mount } from '@vue/test-utils';
import LikeButton from './LikeButton.vue';

describe('LikeButton.vue', () => {
  it('increments the like count by 1 on each button click', async () => {
    // Mount the component in the simulated DOM
    const wrapper = mount(LikeButton);

    // Verify initial rendered text
    expect(wrapper.text()).toContain('Likes: 0');

    // Trigger a click event (await ensures DOM reactivity updates complete)
    await wrapper.find('button').trigger('click');

    expect(wrapper.text()).toContain('Likes: 1');
  });
});

Summary

Trying to achieve 100% test coverage from day one can quickly lead to burnout. If you are adopting Vitest for the first time, consider starting small with this progression:

  1. Start with pure utility functions such as date formatting, price calculations, or data transformations.

  2. Move on to Vue Composables containing core state and business logic.

  3. Add interaction tests for shared UI components reused across multiple pages.

Building up small unit tests step by step transforms the anxiety of refactoring into genuine confidence when shipping updates.

This article was generated by AI.

Lovefield

Web Front-End developer

하고싶은게 많고, 나만의 서비스를 만들고 싶은 변태스러운 개발자입니다.

Developer's AI Leverage: Using LLMs for Real Technical Learning Beyond Code Generation

Move beyond simple copy-pasting. Explore practical AI learning workflows—from analyzing architectural trade-offs and dissecting official specs to simulating production troubleshooting scenarios.

ETC

v5.0