Vue 自动化测试

发布于 2025-05-04

依赖包

经笔者验证、确定支持运行的精确版本,理论上应该支持更多的版本运行。

包名 版本号
node v22.15.0
typescript ~5.8.2
vue ^3.5.13
vitest ^3.0.9
@vue/test-utils ^2.4.6
@testing-library/user-event ^14.6.1
@testing-library/vue ^8.1.0

测试场景

组件类名状态测试

Switch

<template>
  <div class="switch" :class="{ checked }" @click="$emit('update:modelValue', !checked)">
    <div class="dot"></div>
  </div>
</template>

<script lang='ts' setup>
import { defineModel } from 'vue'

const checked = defineModel<boolean>('modelValue', { default: false })
</script>

测试用例

import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import userEvent from '@testing-library/user-event'
import { waitFor } from '@testing-library/vue'
import Switch from './Switch.vue'

/**
 * @vitest-environment jsdom
 */
describe('should toggle switch correctly', async () => {
  const wrapper = mount(Switch, {
    props: {
      modelValue: false,
    },
    attrs: {
      'onUpdate:modelValue': (value: boolean) => wrapper.setProps({ modelValue: value }),
    },
  })
  const radioContainer = wrapper.find('.switch')

  it('Default status', (a) => {
    expect(radioContainer.classes()).not.toContain('checked')
  })

  it('Open Switch', async () => {
    await userEvent.click(radioContainer.element)
    await waitFor(() => {
      expect(wrapper.find('.switch').classes()).toContain('checked')
    })
  })

  it('Close Switch', async () => {
    await userEvent.click(radioContainer.element)
    await waitFor(() => {
      expect(radioContainer.classes()).not.toContain('checked')
    })
  })
})