Trung BìnhVue.js iconVue.js

Testing Vue components với Vitest và Vue Test Utils?

Vue components được test bằng cách mount chúng với @vue/test-utils và assert trên rendered output và emitted events, dùng Vitest làm test runner.

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

describe('Counter', () => {
  it('increments when button clicked', async () => {
    const wrapper = mount(Counter, {
      props: { initialCount: 0 }
    })

    await wrapper.find('button').trigger('click')

    expect(wrapper.text()).toContain('1')
    expect(wrapper.emitted('update')).toBeTruthy()
  })

  it('renders slot content', () => {
    const wrapper = mount(Counter, {
      slots: { default: '<span>Label</span>' }
    })
    expect(wrapper.find('span').exists()).toBe(true)
  })
})

Dùng shallowMount để stub child components.

Test behavior, không test implementation details.

Xem toàn bộ Vue.js cùng filter theo level & chủ đề con.

Mở danh sách Vue.js