javascript / beginner
Snippet
Testing Reactive Counter Logic with Vitest in Vue
Unit testing verifies that small, isolated pieces of code behave as expected. In Vue composables, pure functions returning reactive state can be tested directly using testing frameworks like Vitest without mounting full DOM components.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { ref } from 'vue';import { describe, it, expect } from 'vitest';function useCounter(initial = 0) {const count = ref(initial);const increment = () => { count.value++; };return { count, increment };}describe('useCounter', () => {it('increments the count value by one', () => {const { count, increment } = useCounter(5);increment();expect(count.value).toBe(6);});});
vue
Breakdown
1
describe('useCounter', () => {
Groups related unit tests together under a descriptive suite title.
2
const { count, increment } = useCounter(5);
Initializes the composable state with a starting value of 5.
3
expect(count.value).toBe(6);
Asserts that calling increment() increased the reactive value to exactly 6.