Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

VueJS - Vue Test Utils

Using Vue Test Utils for Component Testing

Vue Test Utils is the official library for testing Vue components. It provides utilities for mounting and interacting with Vue components in tests. This guide covers how to use Vue Test Utils for component testing.

Key Points:

  • Vue Test Utils is the official library for testing Vue components.
  • It provides utilities for mounting components and interacting with them in tests.
  • Vue Test Utils supports various testing scenarios, including unit and integration testing.

Setting Up Vue Test Utils

To start using Vue Test Utils, install it along with a test runner like Jest:


// Install necessary packages
$ npm install @vue/test-utils jest vue-jest babel-jest --save-dev

// Add a basic Jest configuration
// jest.config.js
module.exports = {
  moduleFileExtensions: ['js', 'json', 'vue'],
  transform: {
    '^.+\\.js$': 'babel-jest',
    '^.+\\.vue$': 'vue-jest'
  },
  testEnvironment: 'jsdom'
};
                

Basic Component Testing

To test a Vue component, use Vue Test Utils to mount the component and make assertions:


// MyComponent.vue




// MyComponent.spec.js
import { shallowMount } from '@vue/test-utils';
import MyComponent from './MyComponent.vue';

describe('MyComponent.vue', () => {
  it('renders the correct message', () => {
    const wrapper = shallowMount(MyComponent);
    expect(wrapper.text()).toContain('Hello, Vue!');
  });

  it('increments the count and updates the message when button is clicked', async () => {
    const wrapper = shallowMount(MyComponent);
    wrapper.find('button').trigger('click');
    await wrapper.vm.$nextTick();
    expect(wrapper.text()).toContain('Count is 1');
  });
});
                

Testing Props and Events

Vue Test Utils provides utilities for testing component props and emitted events:


// ChildComponent.vue




// ChildComponent.spec.js
import { shallowMount } from '@vue/test-utils';
import ChildComponent from './ChildComponent.vue';

describe('ChildComponent.vue', () => {
  it('renders the correct message', () => {
    const wrapper = shallowMount(ChildComponent, {
      propsData: { message: 'Hello, World!' }
    });
    expect(wrapper.text()).toContain('Hello, World!');
  });

  it('emits the correct event with payload', async () => {
    const wrapper = shallowMount(ChildComponent);
    wrapper.find('button').trigger('click');
    await wrapper.vm.$nextTick();
    expect(wrapper.emitted('custom-event')[0]).toEqual(['payload']);
  });
});
                

Mocking Dependencies

Use Jest to mock dependencies and control their behavior during tests:


// ApiService.js
export default {
  fetchData() {
    return Promise.resolve('Real data');
  }
};

// MyComponent.vue




// MyComponent.spec.js
import { shallowMount } from '@vue/test-utils';
import MyComponent from './MyComponent.vue';
import ApiService from './ApiService';

jest.mock('./ApiService', () => ({
  fetchData: jest.fn()
}));

describe('MyComponent.vue', () => {
  it('renders mocked data', async () => {
    ApiService.fetchData.mockResolvedValue('Mocked data');
    const wrapper = shallowMount(MyComponent);
    await wrapper.vm.$nextTick();
    expect(wrapper.text()).toContain('Mocked data');
  });
});
                

Testing Slots

Vue Test Utils allows you to test components with slots by providing slot content:


// ParentComponent.vue




// ParentComponent.spec.js
import { shallowMount } from '@vue/test-utils';
import ParentComponent from './ParentComponent.vue';

describe('ParentComponent.vue', () => {
  it('renders slot content', () => {
    const wrapper = shallowMount(ParentComponent, {
      slots: {
        default: '

Slot content

' } }); expect(wrapper.html()).toContain('

Slot content

'); }); });

Best Practices

Follow these best practices when using Vue Test Utils:

  • Write Testable Code: Design your components to be easy to test by keeping them simple and avoiding tight coupling.
  • Use Shallow Mounting: Use shallow mounting for unit tests to isolate the component under test from its dependencies.
  • Test Edge Cases: Test edge cases and invalid inputs to ensure your components handle errors gracefully.
  • Mock External Dependencies: Mock external dependencies to control their behavior and avoid flaky tests.
  • Keep Tests Fast: Write fast tests to ensure quick feedback during development and continuous integration.

Summary

This guide provided an overview of using Vue Test Utils for component testing, including setting up the testing environment, basic component testing, testing props and events, mocking dependencies, testing slots, and best practices. By understanding and utilizing these techniques, you can ensure that your VueJS components are reliable, maintainable, and free of bugs.