@lazy-koala/vite-plugin-auto-testid
v1.0.0
Published
Auto-add data-testid and role attributes to Vue SFC template elements with event handlers
Maintainers
Readme
vite-plugin-auto-testid
Vite 插件,自动为 Vue SFC 模板中含有事件绑定的元素添加 data-testid 和 role 属性,提升自动化测试可行性与无障碍访问性。
功能
- AST 级别解析模板,非正则匹配,准确可靠
- 自动检测
@click/v-on:click等事件绑定 - 为可交互元素添加
data-testid属性(值由组件名 + 事件处理函数名组成) - 为缺少显式
role的非语义化可交互元素自动添加role属性 - 支持自定义
role与事件的映射规则 - 支持生产环境自动禁用
安装
npm install @lazy-koala/vite-plugin-auto-testid -D注意:本插件依赖 @vue/compiler-sfc 和 @vue/compiler-dom,项目需已安装 vue。
使用
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import autoTestId from '@lazy-koala/vite-plugin-auto-testid'
export default defineConfig({
plugins: [
vue(),
autoTestId()
]
})效果
输入
<template>
<img @click="handleConfirm" />
<button @click="handleConfirm">确认</button>
<div @click="count++">{{ count }}</div>
</template>输出
<template>
<img role="button" data-testid="mycomponent_handleconfirm" @click="handleConfirm" />
<button data-testid="mycomponent_handleconfirm" @click="handleConfirm">确认</button>
<div role="button" data-testid="mycomponent-click-1" @click="count++">{{ count }}</div>
</template>配置
import autoTestId from '@lazy-koala/vite-plugin-auto-testid'
autoTestId({
// 指定禁用插件的环境模式,默认 ['production']
disableEnv: ['production'],
// role 与事件映射规则
// key: role 属性值, value: 触发事件名数组(不带 @ 前缀)
// 默认 { button: ['click'] }
roleRules: {
button: ['click'],
link: ['click'],
submitter: ['submit']
},
// 自定义测试属性名,默认 'data-testid'
testIdAttribute: 'data-testid',
})testid 生成规则
| 场景 | 规则 | 示例 |
|---|---|---|
| 简单函数名 @click="handleClick" | {组件小写}_{函数小写} | mybutton_handleclick |
| 内联表达式 @click="count++" | {组件小写}-click-{序号} | mybutton-click-1 |
| 已有 data-testid | 跳过,不覆盖 | - |
role 添加规则
- 非语义化可交互标签(
div、img、span等)→ 根据roleRules添加role - 原生语义标签(
button、a、input等)已具备隐式 role → 跳过 - 已有显式
role属性 → 不覆盖
License
MIT
