Unit Testing Vue Components
Learn how to do unit testing in Vue components with the detailed example of an accordion component.
We'll cover the following
Installation
To begin, make sure to install Jest and Vue 3 compatible versions of the Vue Test Utils and the Vue Testing Library. If we use Vue CLI to scaffold our project but haven’t selected an option to add unit tests, we can do so by running vue add unit-jest
.
After that, the @vue/cli-plugin-unit-jest
installs the necessary libraries, creates the jest.config.js
file and tests
directory in the root
folder, and adds a script to run the tests. The tests
folder has another folder inside, called unit
, with an example.spec.js
file. By default, only .spec
files that are inside of the tests/unit
folder are matched for testing. While it wouldn’t be so bad to keep our tests there, if we have a smaller app, it would be much harder to track which components do have tests in larger apps, where we can have hundreds or even thousands of components.
Therefore, as we’ve established before, it’s best to keep things close to where they belong. We need to modify the jest.config.js
file to update the testMatch
regex and specify the root
directory for the tests. We want to default to src
because Cypress tests are kept outside of it. The reason is that tests with Cypress aren’t necessarily associated with a specific component, but test different user journeys. First, add the rootDir
and testMatch
properties to the jest.config.js
file.
Get hands-on with 1200+ tech skills courses.