Skip to content

Jest + Vue Test Utils 常用 API 对照表

「归属库」「API 名称」「核心用途」「示例代码」分类,清晰区分两者职责,方便日常查阅:

归属库API 名称核心用途示例代码
Jestdescribe分组测试用例(划分模块)describe('ElInput 组件测试', () => { /* 测试用例 */ })
Jesttest/it定义单个测试用例test('输入值变化时触发事件', () => { /* 断言逻辑 */ })
Jestexpect启动断言(包裹待验证值)expect(wrapper.emitted('input')).toBeTruthy()
JesttoBe严格相等校验(===)expect(wrapper.vm.value).toBe('123')
JesttoEqual深相等校验(对象/数组适用)expect(wrapper.vm.form).toEqual({ name: '', age: 0 })
JesttoBeTruthy真值校验(非 null/undefined/0/'' 等)expect(wrapper.find('.el-button').exists()).toBeTruthy()
JesttoBeFalsy假值校验expect(wrapper.find('.hidden').exists()).toBeFalsy()
JesttoContain数组/字符串包含校验expect(wrapper.text()).toContain('提交成功')
JestmockResolvedValue模拟异步函数成功返回api.fetchData.mockResolvedValue({ code: 200 })
JestmockRejectedValue模拟异步函数失败返回api.fetchData.mockRejectedValue(new Error('请求失败'))
JestbeforeEach每个测试用例执行前初始化(如挂载组件)beforeEach(() => { wrapper = mount(MyComponent) })
JestafterEach每个测试用例执行后清理(如销毁组件)afterEach(() => { wrapper.unmount() })
Vue Test Utilsmount完整挂载组件(渲染所有子组件)import { mount } from '@vue/test-utils'; const wrapper = mount(MyComponent)
Vue Test UtilsshallowMount浅挂载组件(不渲染子组件,提升效率)const wrapper = shallowMount(MyComponent)
Vue Test Utilswrapper.find查找组件内 DOM/子组件(返回 Wrapper)const input = wrapper.find('input') / const btn = wrapper.findComponent(ElButton)
Vue Test Utilswrapper.findAll查找多个匹配的 DOM/子组件(返回 WrapperArray)const items = wrapper.findAll('.list-item')
Vue Test Utilsexists()判断查找的元素/组件是否存在expect(wrapper.find('.el-input').exists()).toBe(true)
Vue Test Utilstrigger触发 DOM/组件事件(如点击、输入)wrapper.find('button').trigger('click') / input.trigger('input', { target: { value: '123' } })
Vue Test UtilssetValue给表单元素设置值(输入框、选择器等)wrapper.find('input').setValue('测试内容')
Vue Test Utilstext()获取元素文本内容expect(wrapper.find('.title').text()).toBe('标题')
Vue Test Utilshtml()获取元素 HTML 结构expect(wrapper.find('.content').html()).toContain('<span>内容</span>')
Vue Test Utilsvm访问组件实例(可获取 props/data/methods)expect(wrapper.vm.form.name).toBe('') / wrapper.vm.handleSubmit()
Vue Test Utilsemitted()获取组件触发的自定义事件expect(wrapper.emitted('submit')[0]).toEqual([{ name: '测试' }])
Vue Test UtilssetProps动态设置组件 propsawait wrapper.setProps({ disabled: true })
Vue Test Utilsunmount销毁挂载的组件(清理测试环境)wrapper.unmount()

核心区分原则

  • Jest:负责「测试框架能力」(用例分组、断言匹配、异步模拟、生命周期钩子),是通用测试工具,不绑定 Vue。
  • Vue Test Utils:负责「Vue 组件专属操作」(挂载、DOM 查询、事件触发、组件实例访问),是 Vue 生态专用测试库,需依赖 Jest 等框架运行。

要不要我帮你整理一份Vue 组件测试通用模板,整合上述 API 实现常见场景(表单校验、事件触发、异步请求)的测试用例?

Released under the MIT License.