Blog>
Snippets

Unit Testing with Jest

Showcase how to write and run unit tests for Vue components using Jest, including mocking dependencies and testing computed properties and methods.
// jest.config.js
module.exports = {
  preset: '@vue/cli-plugin-unit-jest',
  testMatch: ['**/*.spec.js']
};
This code defines the Jest configuration for testing Vue components. It tells Jest to use the preset provided by Vue CLI for unit testing and specifies the pattern to match test files.
// ExampleComponent.vue
<template>
  <div>{{ computedMessage }}</div>
</template>

<script>
export default {
  name: 'ExampleComponent',
  props: ['message'],
  computed: {
    computedMessage() {
      return this.message.toUpperCase();
    }
  }
};
</script>
This is a Vue component with a computed property that transforms a prop message to uppercase. The component will be the subject of the unit test.
// ExampleComponent.spec.js
import { shallowMount } from '@vue/test-utils';
import ExampleComponent from '@/components/ExampleComponent.vue';

describe('ExampleComponent', () => {
  it('computes the message to uppercase', () => {
    const wrapper = shallowMount(ExampleComponent, {
      propsData: {
        message: 'hello'
      }
    });
    expect(wrapper.text()).toBe('HELLO');
  });
});
This test file contains a Jest test suite for the ExampleComponent Vue component. It has a single test that ensures the computed property 'computedMessage' correctly transforms the input message to uppercase.
// ExampleComponentWithDependency.vue
<template>
  <div>{{ fetchedData }}</div>
</template>

<script>
import dependency from './dependency';

export default {
  name: 'ExampleComponentWithDependency',
  data() {
    return {
      fetchedData: ''
    };
  },
  created() {
    this.fetchedData = dependency.fetchData();
  }
};
</script>
This Vue component has a dependency that fetches data on creation. The dependency will be mocked in the unit test to control the data that is fetched.
// ExampleComponentWithDependency.spec.js
import { shallowMount } from '@vue/test-utils';
import ExampleComponentWithDependency from '@/components/ExampleComponentWithDependency.vue';
jest.mock('./dependency', () => ({
  fetchData: jest.fn(() => 'Mocked Data')
}));

describe('ExampleComponentWithDependency', () => {
  it('fetches and displays data', () => {
    const wrapper = shallowMount(ExampleComponentWithDependency);
    expect(wrapper.text()).toBe('Mocked Data');
  });
});
The test file for ExampleComponentWithDependency mocks the dependency before running the test. This test ensures that the component is using the mocked function to fetch data and render it correctly.
// Running Jest tests
// Run all tests
npm run test:unit

// Run tests in a specific file
npm run test:unit ExampleComponent.spec.js
These commands are used to run Jest tests. The first command runs all unit tests in the project, while the second command runs only the tests in the specified test file.