Skip to main content

Command Palette

Search for a command to run...

How to unit test a method in a Vue.js component using jest

Published
4 min read
How to unit test a method in a Vue.js component using jest
E

Ethan Patrick is an experienced technology and software content writer with a proven track record of crafting high-quality content for various industries. With a strong understanding of software development, IT, and emerging technologies, John creates informative articles, blog posts, and technical guides that educate and inspire readers.

Testing the logic within your Vue components is a critical part of building robust and maintainable applications. Unit tests focus on isolating small pieces of functionality, in this case, your component methods, and verifying they work exactly as intended.

This guide provides an in-depth walkthrough on how to use Jest and Vue Test Utils to specifically test methods defined within your Vue components.

Prerequisites: Setting Up Your Testing Environment

Before you write your first test, ensure your project is configured correctly. Most modern Vue CLI setups include Jest and Vue Test Utils by default. If you need to install them manually:

npm install --save-dev @vue/test-utils jest babel-jest vue-jest
# Or using yarn
yarn add --dev @vue/test-utils jest babel-jest vue-jest

The Core Tools: Vue Test Utils and Jest

To test Vue components effectively, you need specialized tools. The Top Vuejs Testing Tools typically include Jest as the test runner and assertion library, and @vue/test-utils as the library that provides the necessary methods to mount and interact with Vue instances in a simulated environment.

Step 1: The Component Under Test

Let's define a simple UserAccount.vue component that manages a user's status. We want to test its methods in isolation.

<template>
  <div>
    <p>Status: {{ statusMessage }}</p>
    <button @click="toggleStatus">Toggle Status</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isActive: false
    };
  },
  computed: {
    statusMessage() {
      return this.isActive ? 'Active' : 'Inactive';
    }
  },
  methods: {
    toggleStatus() {
      // This is the method we want to unit test
      this.isActive = !this.isActive;
      this.$emit('statusChanged', this.isActive);
    },
    // Another method to test
    setStatus(status) {
        this.isActive = status;
    }
  }
};
</script>

Step 2: Creating the Test File

We create a corresponding test file, typically named UserAccount.spec.js or UserAccount.test.js. It should be located near the component file or within a dedicated tests/unit directory.

Step 3: Writing the Unit Tests

The key to testing methods in isolation is accessing the component's internal instance, which the mount function from Vue Test Utils provides access to via the wrapper.vm property.

wrapper.vm (ViewModel) is the actual, live Vue instance where your methods, data, and computed properties reside.

Here is how you test the toggleStatus and setStatus methods:

import { mount } from '@vue/test-utils';
import UserAccount from './UserAccount.vue'; // Adjust the path as needed

describe('UserAccount Methods', () => {

  it('correctly toggles the isActive status when toggleStatus method is called', () => {
    // 1. Mount the component
    const wrapper = mount(UserAccount);

    // 2. Access the Vue instance (vm stands for ViewModel)
    const vm = wrapper.vm;

    // Verify initial state
    expect(vm.isActive).toBe(false);
    expect(vm.statusMessage).toBe('Inactive');

    // 3. Call the method directly on the vm instance
    vm.toggleStatus();

    // 4. Assert the resulting state change
    expect(vm.isActive).toBe(true);
    expect(vm.statusMessage).toBe('Active');

    // Call it again to ensure it toggles back
    vm.toggleStatus();
    expect(vm.isActive).toBe(false);
    expect(vm.statusMessage).toBe('Inactive');
  });

  it('sets the status correctly using the setStatus method', () => {
    const wrapper = mount(UserAccount);
    const vm = wrapper.vm;

    expect(vm.isActive).toBe(false);

    // Test setting it to true
    vm.setStatus(true);
    expect(vm.isActive).toBe(true);
    expect(vm.statusMessage).toBe('Active');

    // Test setting it to false
    vm.setStatus(false);
    expect(vm.isActive).toBe(false);
    expect(vm.statusMessage).toBe('Inactive');
  });
});

Step 4: Running Your Tests

Run your tests using your configured command (usually npm test or yarn test):

npm test

Jest will execute the tests and report the results:

 PASS  tests/unit/UserAccount.spec.js
  UserAccount Methods
    ✓ correctly toggles the isActive status when toggleStatus method is called (4ms)
    ✓ sets the status correctly using the setStatus method (1ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.234s

Key Takeaways

Testing methods this way confirms the internal business logic of your components is sound, independent of how the user interface is rendered or interacted with via events.

By isolating methods and testing them directly on the wrapper.vm instance, you ensure reliability and help prevent regressions. For complex enterprise applications, robust testing like this is fundamental to quality vuejs development services, ensuring that every function performs exactly as specified.

If you have methods that rely on asynchronous operations (like API calls), you would use Jest's mocking capabilities (e.g., jest.mock('axios')) and async/await syntax within your tests, but the core principle of accessing wrapper.vm remains the same.

More from this blog

Software & Tech

55 posts