Basics of Unit Testing In Vue

Basics of Unit Testing In Vue

Unit Testing

Testing will let you know if the app you have created will work as you have intended for the end-users. It’s tough to achieve perfection with everything, but the quality is something every developer should strive for. Testing your codes will help you better your software structure. Today, we are talking about unit testing in Vue, but before that, let’s dive right into understanding unit testing.

The three levels of testing are unit testing, integration testing, and end-to-end testing.

So what is unit testing? It is testing individual units of code free from code dependencies. For error-free, consistent code, unit testing is the first line of defense for developers.

It improves the maintainability of the code and is a fundamental part of the TDD (test-driven development) process. 

To constantly execute the unit testing, it is combined with continuous integration. The unit test will help you find bugs and defects early in the development process, long before your app reaches the end user.

Things To Be Tested

Many a time, it is not possible to test everything all the time. Therefore, the focus of testing should be more on the things your end-user will interact with, and get output from.

Inputs such as query strings, props, data, lifecycle methods, and data stores should be checked.

Outputs will include rendered output, data results, events, data store updates, and dispatches.

These key aspects will ensure a seamless experience for your end user. Unit testing complex logic will need updating during the code refactor. 

Other things to keep in mind are,

  • Events such as ‘if that, then that’ should be tested. For example, what will happen if a specific button is clicked?
  • Specific inputs or props should produce specific results.
  • Implementation details, the underlying business logic used by a component to result in an output, based on the input given.

Unit Testing in Vue

For any Single page application framework like Vue, components are the integral parts. Therefore, the unit testing in Vue should be focused on testing these components in a Vue application.

For that, there are testing environments. The key aspects of any good test environment are as below:

  • They make tests fun and easy to write
  • They can help you write tests fast
  • They will execute tests with a single command
  • Tests will run as quickly as possible

These two fit all the aspects in the best possible way:

  • Vite
  • Vitest

They make unit testing in Vue a walk in the park and not a chore. Choosing the right testing environment and framework will encourage you to test more components, and eventually, take you to a better product.

Let’s go deeper into Unit testing tools for Vue.

Tools for Unit Testing in Vue

Unit test framework Vitest and utility library Vue Test Utils are the tools that you can use for unit testing in Vue.

In fact, Vitest can also be used for React, Svelte, Lit, and many more, apart from Vue. Its configuration with Vite makes the execution of the unit test faster. If a developer is familiar with JEst, Vitest would be easy to adapt as the Vites API is compatible with Jest.

1. Vue Test Utils

These are Vue Test Utils functionalities to be aware of:

  • Finding HTML components for testing (findAll(‘h2’))
  • Flushing all Promises (flushPromises())
  • Trigger Events on Click (trigger)
  • Check emitted events (emitted)
  • Mounting components (mount, shallowMount)
  • Setting props data (setProps)

2. Vitest

Vitest provides you with this set of functionalities:

  • Write unit tests (it, describe)
  • Command in-line tool to run tests and check the test coverage
  • See test and coverage results
  • Setup and Teardown (beforeEach, beforeAll, afterEach, afterAll)
  • Check against expected values (expect, toContain, toMatch, etc.)
  • Mocking (mockResolvedValue, mockRejectedValue)

Here, Vue Test Utils provide test utilities that are Vue-specific, and Vitest will provide the generic functionality to write these tests.

Running the Test

Now that you know the tools, here are some of the things to know about running the unit testing in Vue.

  • The naming convention for Vue testing is formatted like <componentName>.spec.js. Here, the component name should be multiple words instead of using just the <header>, so it does not conflict with HTML.
  • Each component of your Vue project will have one unit test file for it. There can be single or multiple unit tests in those unit files.
  • In the component folder, place unit test files in a sub-folder as (src/components/_tests_).

You can run tests in Vitest as follows (an example):

$ npm run test:unit

✓ src/components/__tests__/ProjectHeader.spec.js

✓ src/components/__tests__/ProjectBanner.spec.js

✓ src/components/__tests__/ProjectFooter.spec.js

✓ src/components/__tests__/App.spec.js

  • All available commands that are run via npm for your project will be defined in package.json under the scripts field.
  • Vitest runs tests in the watch mode by default. This will result in the test suite being re-executed on each save. Update the test:unit configuration in package.json and include the run argument as given below, so that Vue will run only once without the watch mode:

“test:unit”: “vitest run –environment jsdom”,

Things To Consider

Here are some things you need to consider while unit testing in Vue.

Code Coverage

It is important to know how much of your source code is actually getting tested when you unit test. 

In Vitest, it is flagged with –coverage

After the unit test is run, the coverage will be reported with the number of statements, branches, functions, and lines that were part of your test.

Moreover, npm run test:ui will load these results in your default web browser to help you see where the coverage is missing in your unit test.

Structure

Some of the important aspects of your Unit testing in Vue are as follows.

  • Each unit test suite will have a related set of unit tests.
  • To create independent test functions, use beforeEach() and afterEach().
  • If there are libraries used within the Vue component that you need to test, create mocks for them.
  • To update prop data within test functions, render components in beforeEach()
  • Test individual components by using shallowMount() rather than mount()

Conclusion

These are the basic components of unit testing in Vue. We have discussed what unit testing is and why it makes sense for Vue. Which components should you be testing and what are the tools for unit testing in Vue? And finally, some things to keep in mind as you run your unit testing.

The most important takeaway here is to focus on the inputs and outputs concerning the end user and keep your code bug-free right at the earlier stages of development.