DEV Community

Cover image for Integrating Jest Testing into an Existing Vue 3 Project with ViteJs
⚡ Nirazan Basnet ⚡ for IntegridSolutions

Posted on

Integrating Jest Testing into an Existing Vue 3 Project with ViteJs

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


Enter fullscreen mode Exit fullscreen mode

Using npm



npm install --save-dev jest jest-environment-jsdom babel-jest @babel/preset-env @vue/vue3-jest @vue/test-utils


Enter fullscreen mode Exit fullscreen mode

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"],
    },
}


Enter fullscreen mode Exit fullscreen mode

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",
                        },
                    },
                ],
            ],
        },
    },
}


Enter fullscreen mode Exit fullscreen mode

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"
},


Enter fullscreen mode Exit fullscreen mode

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 called HelloWorld.spec.js.

  • Add the following code to the HelloWorld.spec.js file:

Hello World Component

HelloWorld Component code



<template>
    <div>
        <div>
            <h1>
                {{ msg }}
            </h1>
            <p>...</p>
        </div>
    </div>
</template>

<script setup>
    defineProps({
        msg: {
            type: String,
            required: true,
        },
    });
</script>


Enter fullscreen mode Exit fullscreen mode

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")
    })
})


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

This command will initialize the Jest testing framework and run the tests.

Jest Testing initialization


🎉 🎉 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)

Collapse
 
chronicstone profile image
Cyprien Thao

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 :

  • incomparable perfs & run time
  • jest-compatible API
  • first class 0 config intégration with vite
  • support for vite plugin API

There might be exceptions, but overall I recommend anyone working on a vite app to use vitest over jest

Collapse
 
schemetastic profile image
Schemetastic (Rodrigo) • Edited

I was wondering about Vitest actually...

But to be fair, it took a while for me to realize that Vitest actually exist, haha.

Collapse
 
blindfish3 profile image
Ben Calder

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 ;)

Collapse
 
nirazanbasnet profile image
⚡ Nirazan Basnet ⚡

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. :)

Collapse
 
yi_cao_ced436862be5ca9006 profile image
yi cao

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.

Collapse
 
tomatopotato27 profile image
Tshering Lama

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!

Collapse
 
nirazanbasnet profile image
⚡ Nirazan Basnet ⚡

Thankyou :)

Collapse
 
vadimcpp profile image
Vadym Kaninskyi

It works! Thank you.

Collapse
 
nirazanbasnet profile image
⚡ Nirazan Basnet ⚡

Ur welcome :)

Collapse
 
yatharthaa profile image
Sandip Bhandari

Awesome article, help me a lot
Thanks

Collapse
 
nirazanbasnet profile image
⚡ Nirazan Basnet ⚡

Thankyou :)

Collapse
 
ravin_regmi_703d409787237 profile image
Ravin Regmi

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.

Collapse
 
nirazanbasnet profile image
⚡ Nirazan Basnet ⚡

Thankyou :)

Collapse
 
sirjamesbrown profile image
James Brown

Curious, i'm getting this using your npm script (kubuntu / node 19) on fresh project

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! 
npm ERR! While resolving: @modules/vue@1.0.0
npm ERR! Found: babel-jest@26.6.3
npm ERR! node_modules/babel-jest
npm ERR!   babel-jest@"^26.6.3" from jest-config@26.6.3
npm ERR!   node_modules/jest-config
npm ERR!     jest-config@"^26.6.3" from @jest/core@26.6.3
npm ERR!     node_modules/@jest/core
npm ERR!       @jest/core@"^26.6.3" from jest@26.6.3
npm ERR!       node_modules/jest
npm ERR!         peer jest@">= 24 < 27 " from vue-jest@5.0.0-alpha.10
npm ERR!         node_modules/vue-jest
npm ERR!         1 more (the root project)
npm ERR!       1 more (jest-cli)
npm ERR!     jest-config@"^26.6.3" from jest-cli@26.6.3
npm ERR!     node_modules/jest-cli
npm ERR!       jest-cli@"^26.6.3" from jest@26.6.3
npm ERR!       node_modules/jest
npm ERR!         peer jest@">= 24 < 27 " from vue-jest@5.0.0-alpha.10
npm ERR!         node_modules/vue-jest
npm ERR!         1 more (the root project)
npm ERR!     2 more (jest-runner, jest-runtime)
npm ERR!   peer babel-jest@">= 24 < 27" from vue-jest@5.0.0-alpha.10
npm ERR!   node_modules/vue-jest
npm ERR!     dev vue-jest@"^5.0.0-alpha.10" from the root project
npm ERR!   1 more (the root project)
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! dev @vue/vue3-jest@"*" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: babel-jest@29.6.2
npm ERR! node_modules/babel-jest
npm ERR!   peer babel-jest@"29.x" from @vue/vue3-jest@29.2.4
npm ERR!   node_modules/@vue/vue3-jest
npm ERR!     dev @vue/vue3-jest@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sirjamesbrown profile image
James Brown

assuming i'm not just being silly