Vue Jest 是一個測試框架,用於為 Vue 應用程序編寫單元測試和集成測試。在本文中,我將從多個方面詳細介紹 Vue Jest 的用途、功能和用法。
一、安裝和配置
Vue Jest 的使用前必須安裝,使用 npm 或者 yarn:
npm i -D jest @vue/test-utils vue-jest babel-jest jest-serializer-vue
在 package.json 中添加:
"scripts": {
"test": "jest"
},
"jest": {
"preset": "@vue/cli-plugin-unit-jest/presets/typescript-and-babel",
"transform": {
"^.+\\.vue$": "vue-jest",
".+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$": "jest-transform-stub",
"^.+\\.js$": "babel-jest"
}
}
這裡的 preset 需要根據實際項目進行配置,包括語言、框架等。
二、單元測試和集成測試
Vue Jest 可以用於編寫單元測試和集成測試。下面是一個 Vue 組件的示例代碼和相應的測試代碼。
Vue 組件代碼:
<template>
<div>
<p>{{ message }}</p>
<button @click="onClick">Increment</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
},
computed: {
message() {
return `Count: ${this.count}`
}
},
methods: {
onClick() {
this.count++
}
}
}
</script>
接下來是這個組件的單元測試:
import { shallowMount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'
describe('MyComponent', () => {
it('renders message when count is 0', () => {
const wrapper = shallowMount(MyComponent)
expect(wrapper.text()).toMatch('Count: 0')
})
it('renders message when count is incremented', async () => {
const wrapper = shallowMount(MyComponent)
await wrapper.find('button').trigger('click')
expect(wrapper.text()).toMatch('Count: 1')
})
})
除了單元測試,Vue Jest 也支持集成測試。下面是一個集成測試的示例代碼,用於測試整個應用程序的行為。
import { mount } from '@vue/test-utils'
import App from '@/App.vue'
describe('App', () => {
it('increments count when button is clicked', async () => {
const wrapper = mount(App)
await wrapper.find('button').trigger('click')
expect(wrapper.vm.count).toBe(1)
})
})
三、mock 和 spy
Vue Jest 還支持 mock 和 spy 的功能。這對於測試一些與接口等外部依賴有關的邏輯非常有用。
下面是一個 mock 的示例代碼,用於模擬一個返回固定數據的接口:
import { shallowMount } from '@vue/test-utils'
import axios from 'axios'
import MyComponent from '@/components/MyComponent.vue'
jest.mock('axios')
describe('MyComponent', () => {
it('displays data from API', async () => {
const data = {
message: 'Hello World!'
}
axios.get.mockResolvedValue(data)
const wrapper = shallowMount(MyComponent)
await wrapper.vm.loadData()
expect(wrapper.text()).toMatch(data.message)
})
})
And here’s a spy example, which monitors how a certain method is called:
import { mount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'
describe('MyComponent', () => {
it('calls method when button is clicked', async () => {
const wrapper = mount(MyComponent)
const onClickSpy = jest.spyOn(wrapper.vm, 'onClick')
await wrapper.find('button').trigger('click')
expect(onClickSpy).toHaveBeenCalled()
})
})
四、總結
本文介紹了 Vue Jest 的安裝、配置、單元測試和集成測試,以及 mock 和 spy 的功能。Vue Jest 是一個強大的測試框架,可以為 Vue 應用程序提供全面的測試支持。
完整代碼請訪問Github。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/282926.html