我们为什么要单元测试呢,单元测试可以解决最小区域的问题,可能会比较耗时间,但对开发来说至关重要。 写单元测试的时间可能会比开发更长,往往收获会小于付出的,让我们动起来吧
第一个例子
//Components.tsx
import { defineComponent } from 'vue'
export default defineComponent({
name: 'VueComponent',
setup() {
return ()=>(
<div>Vue Component</div>
)
}
})
复制代码
//components.test.js
import { mount } from "@vue/test-utils";
import comp from './Components.tsx'
describe('component.tsx',() => {
it('初始化一个组件', async ()=> {
const wrapper = mount(comp);
expect(wrapper.find('div').text()).toBe('Vue Component');
})
})
复制代码
上面的测试单元部分验证出了div中的文本内容是否相等,
第二个例子
//ConditionalRendering.tsx
import { defineComponent, ref } from 'vue'
export default defineComponent({
name: 'ConditionalRendering',
setup() {
const admin = ref(false);
return () =>(
<nav>
<a id="profile" href="/profile">My Profile</a>
<a v-show={admin} id="admin" href="/admin">Admin</a>
</nav>
)
}
})
复制代码
//conditionalrendering.test.js
import { mount } from "@vue/test-utils";
import conditionalrendering from './ConditionalRendering.tsx'
describe('conditionalrendering.tsx', () => {
it('渲染profile', async()=>{
const wrapper = mount(conditionalrendering);
expect(wrapper.find('#profile').text()).toBe('My Profile')
})
it('能渲染admin', async()=>{
const wrapper = mount(conditionalrendering, {
data(){
return {
admin: true
}
}
});
expect(wrapper.find('#admin').isVisible()).toBe(true);
})
it('不能渲染admin', async()=>{
const wrapper = mount(conditionalrendering);
expect(wrapper.find('#admin').isVisible()).toBe(false);
})
})
复制代码
上面的测试例子验证当前内容是否渲染和是否能渲染
编写单元测试文件,用于验证组件的逻辑和业务的完整性。根据实际情况,复杂程度也会大不相同,你的每行代码对于团队里的你来说是很有成就感的一件事。
新人码农一枚, 大家一起加油!!!!
本篇基于
- "@vue/test-utils": "^2.0.0-alpha.8",
- "vue": "^3.0.11",
- "jest": "^25.2.7",
- "babel-jest": "^25.2.6",