Testing Vue components in Jest requires using @vue/test-utils:
1. Install Dependencies:
bashnpm install --save-dev @vue/test-utils jest vue-jest
2. Configure 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. Testing Vue Components:
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. Testing Props:
javascripttest('renders with props', () => { const wrapper = mount(Counter, { propsData: { initialCount: 5 } }); expect(wrapper.text()).toContain('Count: 5'); });
5. Testing Events:
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. Testing Computed Properties:
javascripttest('computes double count', () => { const wrapper = mount(Counter, { data() { return { count: 5 }; } }); expect(wrapper.vm.doubleCount).toBe(10); });
7. Testing Slots:
javascripttest('renders slot content', () => { const wrapper = mount(MyComponent, { slots: { default: 'Custom content' } }); expect(wrapper.text()).toContain('Custom content'); });
Best Practices:
- Use
mountfor full rendering,shallowMountfor shallow rendering - Test user interactions and events
- Verify props and emitted events
- Test computed properties and methods
- Use
setDataandsetPropsto update state - Keep tests simple and maintainable