Vue.js
Vue.js 是一个易于上手、高性能且多功能的构建 Web 用户界面的框架。你可以使用 WebdriverIO 及其浏览器运行器在真实浏览器中直接测试 Vue.js 组件。
设置
要在 Vue.js 项目中设置 WebdriverIO,请参照我们组件测试文档中的指南。确保在运行器选项中选择 vue
作为预设,例如:
// wdio.conf.js
export const config = {
// ...
runner: ['browser', {
preset: 'vue'
}],
// ...
}
Vue 预设需要安装 @vitejs/plugin-vue
。此外,我们建议使用 Testing Library 来将组件渲染到测试页面中。因此,你需要安装以下额外的依赖项:
- npm
- Yarn
- pnpm
npm install --save-dev @testing-library/vue @vitejs/plugin-vue
yarn add --dev @testing-library/vue @vitejs/plugin-vue
pnpm add --save-dev @testing-library/vue @vitejs/plugin-vue
然后你可以通过运行以下命令启动测试:
npx wdio run ./wdio.conf.js
编写测试
假设你有以下 Vue.js 组件:
./components/Component.vue
<template>
<div>
<p>Times clicked: {{ count }}</p>
<button @click="increment">increment</button>
</div>
</template>
<script>
export default {
data: () => ({
count: 0,
}),
methods: {
increment() {
this.count++
},
},
}
</script>
在你的测试中,将组件渲染到 DOM 中并对其进行断言。我们建议使用 @vue/test-utils
或 @testing-library/vue
将组件附加到测试页面。要与组件交互,请使用 WebdriverIO 命令,因为它们的行为更接近于实际用户交互,例如:
- @vue/test-utils
- @testing-library/vue
vue.test.js
import { $, expect } from '@wdio/globals'
import { mount } from '@vue/test-utils'
import Component from './components/Component.vue'
describe('Vue Component Testing', () => {
it('increments value on click', async () => {
// The render method returns a collection of utilities to query your component.
const wrapper = mount(Component, { attachTo: document.body })
expect(wrapper.text()).toContain('Times clicked: 0')
const button = await $('aria/increment')
// Dispatch a native click event to our button element.
await button.click()
await button.click()
expect(wrapper.text()).toContain('Times clicked: 2')
await expect($('p=Times clicked: 2')).toExist() // same assertion with WebdriverIO
})
})