乐闻世界logo
搜索文章和话题

How to test Vue components in Jest? How to use @vue/test-utils?

2月19日 19:15

Testing Vue components in Jest requires using @vue/test-utils:

1. Install Dependencies:

bash
npm 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:

javascript
import { 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:

javascript
test('renders with props', () => { const wrapper = mount(Counter, { propsData: { initialCount: 5 } }); expect(wrapper.text()).toContain('Count: 5'); });

5. Testing Events:

javascript
test('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:

javascript
test('computes double count', () => { const wrapper = mount(Counter, { data() { return { count: 5 }; } }); expect(wrapper.vm.doubleCount).toBe(10); });

7. Testing Slots:

javascript
test('renders slot content', () => { const wrapper = mount(MyComponent, { slots: { default: 'Custom content' } }); expect(wrapper.text()).toContain('Custom content'); });

Best Practices:

  • Use mount for full rendering, shallowMount for shallow rendering
  • Test user interactions and events
  • Verify props and emitted events
  • Test computed properties and methods
  • Use setData and setProps to update state
  • Keep tests simple and maintainable
标签:Jest