Search⌘ K
AI Features

Testing a Component

Explore how to set up Jest configuration and test Vue.js single file components. Understand the challenges of testing nested components and discover shallow rendering to isolate unit tests and prevent side effects from child components.

Jest Configuration

Let’s add the following Jest configuration in the package.json:

Markdown
{
"jest": {
"moduleNameMapper": {
"@/([^\\.]*).vue$": "<rootDir>/src/$1.vue",
"@/([^\\.]*)$": "<rootDir>/src/$1.js",
"^vue$": "vue/dist/vue.common.js"
},
"moduleFileExtensions": [
"js",
"vue"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/jest-vue-preprocessor"
}
}

moduleFileExtensions will tell Jest which extensions to look for, whereas transform will tell it which preprocessor to use for a file extension.

Lastly, let’s add a test script to the package.json:

Markdown
{
"scripts": {
"test": "jest"
}
}

Single File Component

We will start our example by using single file components.

Step 1:

Let’s first create a MessageList.vue component under src/components:

HTML
<template>
<ul>
<li v-for="message in messages">
{{ message }}
</li>
</ul>
</template>
<script>
export default {
name: "list",
props: ["messages"]
};
</script>

Step 2:

Now update ...