Bài 8: Testing trong Vue.js 3

Bài 8: Testing trong Vue.js 3

Viết code mà không test giống như “đi trên dây không lưới an toàn”. Testing giúp đảm bảo:

  • Code chạy đúng như mong đợi.

  • Giảm bug khi refactor.

  • Tăng độ tin cậy của dự án.

Trong Vue.js 3, bạn có thể dùng:

  1. Unit Test với Vitest / Jest

  2. Component Test với Vue Test Utils

  3. E2E Test với Cypress / Playwright

1. Unit Test với Vitest

Cài đặt Vitest

npm install -D vitest @vitejs/plugin-vue

Thêm script vào package.json:

"scripts": {
  "test": "vitest"
}

Ví dụ test hàm đơn giản

Tạo src/utils/math.js:

Ví dụ test hàm đơn giản

Tạo src/utils/math.js:

Tạo tests/math.test.js:

import { describe, it, expect } from 'vitest'
import { add } from '../src/utils/math'

describe('math utils', () => {
  it('cộng 2 số đúng', () => {
    expect(add(2, 3)).toBe(5)
  })
})

Chạy test:

npm run test

2. Component Test với Vue Test Utils

Cài đặt

npm install -D @vue/test-utils

Ví dụ test component

Tạo src/components/Counter.vue:

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="count++">Increment</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>

Test tests/Counter.test.js:

import { mount } from '@vue/test-utils'
import { describe, it, expect } from 'vitest'
import Counter from '../src/components/Counter.vue'

describe('Counter.vue', () => {
  it('render với count = 0', () => {
    const wrapper = mount(Counter)
    expect(wrapper.text()).toContain('Count: 0')
  })

  it('tăng count khi click', async () => {
    const wrapper = mount(Counter)
    await wrapper.find('button').trigger('click')
    expect(wrapper.text()).toContain('Count: 1')
  })
})

3. E2E Test với Cypress

Cài đặt Cypress

npm install -D cypress

Chạy Cypress lần đầu:

npx cypress open

Ví dụ test E2E

Giả sử app chạy ở http://localhost:5173 (Vite).

Tạo file cypress/e2e/home.cy.js:

Ví dụ test E2E

Giả sử app chạy ở http://localhost:5173 (Vite).

Tạo file cypress/e2e/home.cy.js:

Chạy E2E test:

npx cypress run

4. Playwright (thay thế Cypress)

Nếu muốn automation test nhanh hơn, bạn có thể dùng Playwright (Microsoft).
Cú pháp gần giống Cypress, nhưng hỗ trợ đa trình duyệt mạnh mẽ hơn.

Ví dụ test với Playwright:

import { test, expect } from '@playwright/test'

test('homepage có tiêu đề', async ({ page }) => {
  await page.goto('http://localhost:5173')
  await expect(page.locator('h1')).toHaveText('Hello Vue')
})

🎯 Tổng kết

  • Unit Test (Vitest/Jest): test logic nhỏ (hàm, store).

  • Component Test (Vue Test Utils): test UI component.

  • E2E Test (Cypress/Playwright): test toàn bộ flow của ứng dụng.

👉 Kết hợp cả 3 loại test sẽ giúp dự án Vue.js 3 an toàn, dễ bảo trì, ít bug khi nâng cấp.