在 Jest 中测试 Vue 组件需要使用 @vue/test-utils:
1. 安装依赖:
bashnpm install --save-dev @vue/test-utils jest vue-jest
2. 配置 Jest:
javascript// jest.config.js module.exports = { preset: '@vue/cli-plugin-unit-jest', moduleFileExtensions: ['js', 'json', 'vue'], transform: { '^.+\\.vue$': 'vue-jest', '^.+\\.js$': 'babel-jest', }, };
3. 测试 Vue 组件:
javascriptimport { mount } from '@vue/test-utils'; import Counter from '@/components/Counter.vue'; describe('Counter.vue', () => { test('renders initial count', () => { const wrapper = mount(Counter); expect(wrapper.text()).toContain('Count: 0'); }); test('increments count when button clicked', async () => { const wrapper = mount(Counter); const button = wrapper.find('button'); await button.trigger('click'); expect(wrapper.text()).toContain('Count: 1'); }); });
4. 测试 Props:
javascripttest('renders with props', () => { const wrapper = mount(Counter, { propsData: { initialCount: 5 } }); expect(wrapper.text()).toContain('Count: 5'); });
5. 测试事件:
javascripttest('emits increment event', async () => { const wrapper = mount(Counter); const button = wrapper.find('button'); await button.trigger('click'); expect(wrapper.emitted('increment')).toBeTruthy(); expect(wrapper.emitted('increment').length).toBe(1); });
6. 测试计算属性:
javascripttest('computes double count', () => { const wrapper = mount(Counter, { data() { return { count: 5 }; } }); expect(wrapper.vm.doubleCount).toBe(10); });
7. 测试插槽:
javascripttest('renders slot content', () => { const wrapper = mount(MyComponent, { slots: { default: 'Custom content' } }); expect(wrapper.text()).toContain('Custom content'); });
最佳实践:
- 使用
mount进行完整渲染,shallowMount进行浅渲染 - 测试用户交互和事件
- 验证 props 和 emitted 事件
- 测试计算属性和方法
- 使用
setData和setProps更新状态 - 保持测试简单和可维护