Integrating Jest Testing into an Existing Vue 3 Project with ViteJs
Tags: javascript, testing, vue, webdev
Published: 2023-07-07 04:54:50

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](https://jestjs.io/).

**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](https://vuejs.org/) and [Vite](https://vitejs.dev/).

## 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**
```bash
yarn add jest jest-environment-jsdom babel-jest @babel/preset-env @vue/vue3-jest @vue/test-utils -D
```

**Using npm**
```bash
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:

```javascript
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 <rootDir>/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:

```javascript
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:

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

- 
Add the following code to the `HelloWorld.spec.js` file:

![Hello World Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/78mktzb23tu4m4460qb3.png)

`HelloWorld Component code`

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

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

`HelloWorld Spec Test code`

```javascript
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:

```bash
yarn unit:test
```

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

![Jest Testing initialization](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sk0orm7oydh7fwzcexkz.gif)

---

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