Vue.js 3.0 Tutorial
Vue.js 3.0 Component Advanced
Vue.js 3.0 Transitions & Animations
Vue.js 3.0 Reusable & Combinable
Vue.js 3.0 Advanced
Vue.js 3.0 Tools
Vue.js 3.0 Scale
Vue.js 3.0 Accessibility
Vue.js 3.0 Migrating from Vue2
Vue.js 3.0 Contribute Documentation
Vue.js 3.0 API References
Vue.js 3.0 Style Guide
Testing is an essential aspect of modern web development, and Vue 3 provides excellent support for testing your components and applications. Vue Test Utils is the official unit testing utility library for Vue.js. It allows you to mount Vue components in isolation and simulate user interactions.
Here is a step-by-step guide to create and test a simple Vue 3 component:
Step 1: Initialize your Vue project.
You can create a new Vue 3 project using the Vue CLI:
npm install -g @vue/cli vue create my-project
Remember to choose Vue 3 when asked which version of Vue to use.
Step 2: Install the necessary testing libraries.
You will need Vue Test Utils, Jest (a JavaScript testing framework), and vue-jest (to handle transformations of Vue files) as dev dependencies. You can install them with npm:
npm install --save-dev @vue/test-utils jest @vue/vue3-jest
Step 3: Create a Jest configuration file.
Create a jest.config.js
file in your project root and paste the following code into it:
module.exports = { testEnvironment: 'jsdom', moduleFileExtensions: [ 'js', 'json', // tell Jest to handle `*.vue` files 'vue' ], transform: { // process `*.vue` files with `vue-jest` '.*\\.(vue)$': '@vue/vue3-jest' }, snapshotSerializers: [ 'jest-serializer-vue' ] }
Step 4: Create a component.
In your src/components
directory, create a new file called Greeting.vue
:
<template> <div> {{ message }} </div> </template> <script> export default { data() { return { message: 'Hello Vue 3!' } } } </script>
Step 5: Create a test.
In your tests/unit
directory, create a new file called Greeting.spec.js
:
import { mount } from '@vue/test-utils' import Greeting from '@/components/Greeting.vue' describe('Greeting.vue', () => { it('renders a message', () => { const wrapper = mount(Greeting) expect(wrapper.text()).toMatch('Hello Vue 3!') }) })
This test will mount the Greeting component in isolation and then check if its rendered text matches 'Hello Vue 3!'.
Step 6: Run your tests.
You can add a script to your package.json
file to run your Jest tests:
"scripts": { "test:unit": "jest" }
Then you can run your tests with the following command:
npm run test:unit
This will run Jest, which will find all the test files in your project and run them. If the text of the rendered Greeting component matches 'Hello Vue 3!', the test will pass.