In my recent experience, I faced the challenge of integrating the Jest testing framework into an existing Vue3 js project that was built with Vite. I encountered difficulty finding helpful installation guides on various blogs. However, after multiple attempts and putting in a lot of effort, I eventually found a solution. In this blog post, I aim to provide a step-by-step installation guide that can assist others who may encounter the same challenge.
Jest Unit Testing 🧪
Jest, developed by Facebook, is a widely-used JavaScript testing framework. It is specifically designed for testing JavaScript applications, including frontend frameworks like React, Vue, and Angular, as well as backend Node.js applications. The core objective of Jest is to provide users with a user-friendly and comprehensive testing experience, achieved through its extensive feature set and inclusive built-in functionalities. You can find more information about Jest here.
Prerequisites 📋
Before proceeding, ensure that you have the following prerequisites in place:
Node.js (version 14 or above) and npm (Node Package Manager) installed on your machine.
Basic knowledge of Vue.js and the Vite build tool. If needed, you can refer to the documentation for Vue3js and Vite.
Step 1: Initialize Jest in Your Project 🚀
To begin, navigate to the root directory of your Vite + Vue 3 project using your preferred command-line interface. Execute the following command to install the necessary Jest packages:
Using yarn
yarn add jest jest-environment-jsdom babel-jest @babel/preset-env @vue/vue3-jest @vue/test-utils -D
Using npm
npm install --save-dev jest jest-environment-jsdom babel-jest @babel/preset-env @vue/vue3-jest @vue/test-utils
Step 2: Configure Jest ⚙️
Once the installation is complete, you need to configure Jest by creating a new file named jest.config.js
in the root directory of your project. Include the following content in the file:
module.exports = {
testEnvironment: "jsdom",
transform: {
"^.+\\.vue$": "@vue/vue3-jest",
"^.+\\js$": "babel-jest",
},
testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(js|ts)$",
moduleFileExtensions: ["vue", "js"],
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
},
coveragePathIgnorePatterns: ["/node_modules/", "/tests/"],
coverageReporters: ["text", "json-summary"],
// Fix in order for vue-test-utils to work with Jest 29
// https://test-utils.vuejs.org/migration/#test-runners-upgrade-notes
testEnvironmentOptions: {
customExportConditions: ["node", "node-addons"],
},
}
Key findings from the above code,
The testEnvironment option is set to "jsdom", which specifies the test environment to be used. In this case, it utilizes JSDOM, a JavaScript implementation of the web standards that simulates a browser-like environment during testing.
The transform option defines how different file types are transformed during testing. Specifically, files ending with the .vue extension are transformed using @vue/vue3-jest, which is a Jest transformer designed for Vue 3 Single File Components (SFCs). JavaScript files (.js) are transformed using babel-jest.
The testRegex option sets a regular expression pattern to match test files. It searches for files located in the /tests/ directory or those with a .test.js or .spec.js extension. This pattern allows Jest to discover and run test files that match this criteria.
The moduleFileExtensions option specifies the file extensions that Jest should consider as module files. In this case, it includes .vue
and .js
extensions.
The moduleNameMapper option specifies how module imports should be resolved. It maps the commonly used @ alias in Vue projects to the src directory. For example, @/example will be resolved to /src/example.
The coveragePathIgnorePatterns option defines patterns of files or directories that should be ignored when calculating code coverage reports. In this case, it excludes files in the /node_modules/ and /tests/ directories.
The coverageReporters option specifies the reporters to be used for code coverage reporting. It uses the text reporter to display coverage information in the console and the json-summary reporter to generate a summary in JSON format.
The testEnvironmentOptions option provides additional options specific to the test environment. It sets the customExportConditions to ["node", "node-addons"], which is a workaround to make vue-test-utils work with Jest 29.
Step 3: Configure Babel Js 🔧
To configure Babel JS in your project, follow these steps:
Create a new file called
babel.config.js
in the root directory of your project.Add the following code to the
babel.config.js
file:
module.exports = {
env: {
test: {
presets: [
[
"@babel/preset-env",
{
targets: {
node: "current",
},
},
],
],
},
},
}
The purpose of this code is to export a configuration object that specifies the Babel presets to be used when running tests in the test environment. The env
property defines different environments and their corresponding configuration settings. In this case, the env.test.presets
property specifies an array of Babel presets to be applied in the test environment.
These presets consist of a collection of Babel plugins and configurations bundled together for specific use cases. The @babel/preset-env
preset is used to automatically determine the Babel transformations and polyfills required based on the target environment. In this example, the target environment is set to node: "current"
, which ensures that the code is transpiled to a version of JavaScript compatible with the current Node.js version used for testing.
Step 3: Update package.json
file 📦
To update the package.json
file, follow these steps:
Locate the "scripts" section in the package.json file.
Add the following line to the "scripts" section:
"scripts": {
...
...
"test:unit": "jest"
},
In this case, the "test:unit"
script is defined to run unit tests. The "jest" command is specified as the executable command or package to be executed when running the script. By setting it to "jest"
, the Jest testing framework will be used.
Step 4: Writing Your First Test ✍️
Now, it's time to write your first test case. I usually prefer to create a test file within the same component.
Create a new component called
HelloWorld
and also create a file calledHelloWorld.spec.js
.Add the following code to the
HelloWorld.spec.js
file:
HelloWorld Component code
<template>
<div>
<div>
<h1>
{{ msg }}
</h1>
<p>...</p>
</div>
</div>
</template>
<script setup>
defineProps({
msg: {
type: String,
required: true,
},
});
</script>
HelloWorld Spec Test code
import HelloWorld from "./HelloWorld.vue"
import { mount } from "@vue/test-utils"
describe("HelloWorld", () => {
it("renders properly", () => {
const wrapper = mount(HelloWorld, { props: { msg: "Hello Jest" } })
expect(wrapper.text()).toContain("Hello Jest")
})
})
Step 5: Run the Tests 🏃♂️
To execute the tests, follow these steps:
Open your command-line interface.
Navigate to the root directory of your project.
Run the following command:
yarn unit:test
This command will initialize the Jest testing framework and run the tests.
🎉 🎉 Hooray and congratulations! 🥳 You've successfully installed Jest and set up unit testing for your Vite + Vue 3 project. 🚀 Now you can write and run tests to ensure the correctness and reliability of your Vue components. By embracing a test-driven development approach, you'll enhance the overall quality of your application and catch bugs early in the development cycle. 💪
Remember to craft comprehensive test cases that cover various scenarios and edge cases, extracting the maximum benefit from your unit testing efforts. Happy testing! 🎯 🧪
Keep on Hacking !!
Top comments (15)
Although the guide in itself is pretty well written, I don't really see why would one want to use jest in a vite app, in a world where vitest exists.
Vitest gives you :
There might be exceptions, but overall I recommend anyone working on a vite app to use vitest over jest
I was wondering about Vitest actually...
But to be fair, it took a while for me to realize that Vitest actually exist, haha.
I just moved a Sveltekit project from Jest to Vitest and it was fairly straightforward. It's possible to retain the Jest test helpers so I only had a few trivial changes in the tests themselves and otherwise just some config changes.
Try it! Then you'll have some material for a follow up article ;)
Thanks for replying. I truly understand that but the requirement here is to integrate JEST so and it is stable and widely used so. But in future definitely I will research Vitest and will write a blog about it. :)
I have a Vite repository with only version 3, but the latest Vitest requires version 5 or above. Instead, I might choose Jest, which is not coupled with the framework.
Overall, this blog post has given me the confidence and knowledge to integrate Jest testing seamlessly into my Vue 3 project with ViteJs. It's a fantastic resource for any Vue developer looking to level up their testing game. Thank you for sharing this informative guide!
Thankyou :)
It works! Thank you.
Ur welcome :)
Awesome article, help me a lot
Thanks
Thankyou :)
Great article with step by step guide to integrate in my Vue 3 project
This is exactly what I was looking for...
Hope to see more of such posts.
Thankyou :)
Curious, i'm getting this using your npm script (kubuntu / node 19) on fresh project
assuming i'm not just being silly