### Start Docs Development Server Source: https://github.com/vuejs/test-utils/blob/main/README.md Run this command to start the documentation development server locally. ```bash pnpm docs:dev ``` -------------------------------- ### Install a Wrapper Plugin Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/extending-vtu/plugins.md Install a plugin by calling `config.plugins.VueWrapper.install()`. This must be done before mounting a component. Optionally, pass options to the install method. ```javascript import { config } from '@vue/test-utils' // locally defined plugin, see "Writing a Plugin" import MyPlugin from './myPlugin' // Install a plugin onto VueWrapper config.plugins.VueWrapper.install(MyPlugin) ``` ```javascript config.plugins.VueWrapper.install(MyPlugin, { someOption: true }) ``` -------------------------------- ### Full Teleport Test Setup Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/teleport.md This example demonstrates the complete setup for testing teleported components, including creating a teleport target in the DOM and asserting emitted events. ```ts import { mount } from '@vue/test-utils' import Navbar from './Navbar.vue' import Signup from './Signup.vue' beforeEach(() => { // create teleport target const el = document.createElement('div') el.id = 'modal' document.body.appendChild(el) }) afterEach(() => { // clean up document.body.innerHTML = '' }) test('teleport', async () => { const wrapper = mount(Navbar) const signup = wrapper.getComponent(Signup) await signup.get('input').setValue('valid_username') await signup.get('form').trigger('submit.prevent') expect(signup.emitted().signup[0]).toEqual(['valid_username']) }) ``` -------------------------------- ### global.provide Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Provides data to be received in a setup function via inject. ```APIDOC ## global.provide ### Description Provides data to be received in a `setup` function via `inject`. ### Signature ```ts provide?: Record ``` ### Example ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' test('global.provide', () => { const wrapper = mount(Component, { global: { provide: { Theme: 'dark' } } }) console.log(wrapper.html()) //=>
Theme is dark
}) ``` ### Example (Symbol Key) ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' const ThemeSymbol = Symbol() mount(Component, { global: { provide: { [ThemeSymbol]: 'value' } } }) ``` ``` -------------------------------- ### Show Component with Script Setup Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/essentials/passing-data.md A simple Vue component using ` ``` -------------------------------- ### Testing Asynchronous Setup with Suspense Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/async-suspense.md Shows how to test a component with an asynchronous `setup` function by wrapping it in a `Suspense` component. This mirrors how such components are handled in a Vue application. ```javascript const Async = defineComponent({ async setup() { // await something } }) test('Async component', async () => { const TestComponent = defineComponent({ components: { Async }, template: '' }) const wrapper = mount(TestComponent) await flushPromises() // ... }) ``` -------------------------------- ### Provide Keyed `useStore` using `global.plugins` Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vuex.md Installs the Vuex store with a specific injection key using the `global.plugins` mounting option. ```javascript // app.spec.js import { createStore } from 'vuex' import { key } from './store' const store = createStore({ /* ... */ }) const wrapper = mount(App, { global: { // to pass options to plugins, use the array syntax. plugins: [[store, key]] } }) ``` -------------------------------- ### Basic Test Setup for Navbar Component Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/teleport.md Initial test setup for the Navbar component. This will produce a warning about a missing Teleport target. ```typescript import { mount } from '@vue/test-utils' import Navbar from './Navbar.vue' import Signup from './Signup.vue' test('emits a signup event when valid', async () => { const wrapper = mount(Navbar) }) ``` -------------------------------- ### global.plugins Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Installs plugins on the mounted component, with support for options and arguments. ```APIDOC ## global.plugins ### Description Installs plugins on the mounted component. ### Signature ```ts plugins?: (Plugin | [Plugin, ...any[]])[] ``` ### Example (Basic) ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' import myPlugin from '@/plugins/myPlugin' test('global.plugins', () => { mount(Component, { global: { plugins: [myPlugin] } }) }) ``` ### Example (With Options) ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' test('global.plugins with options', () => { mount(Component, { global: { plugins: [Plugin, [PluginWithOptions, 'argument 1', 'another argument']] } }) }) ``` ``` -------------------------------- ### Use a Basic Wrapper Plugin Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/extending-vtu/plugins.md After installing a plugin, you can use its added properties directly on the wrapper instance in your component specs. ```javascript // component.spec.js const wrapper = mount({ template: `

🔌 Plugin

` }) console.log(wrapper.$el.innerHTML) // 🔌 Plugin ``` -------------------------------- ### Install Vitest for Vue Projects Source: https://github.com/vuejs/test-utils/blob/main/docs/installation/index.md Install Vitest as a development dependency. It is the recommended test runner for Vue projects and works seamlessly with Vite. ```shell npm install --save-dev vitest ``` -------------------------------- ### Installing Global Plugins Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Use `global.plugins` to install Vue plugins on the mounted component. This allows components to access plugin functionalities during tests. ```javascript import { mount } from '@vue/test-utils' import Component from './Component.vue' import myPlugin from '@/plugins/myPlugin' test('global.plugins', () => { mount(Component, { global: { plugins: [myPlugin] } }) }) ``` ```javascript import { mount } from '@vue/test-utils' import Component from './Component.vue' test('global.plugins with options', () => { mount(Component, { global: { plugins: [Plugin, [PluginWithOptions, 'argument 1', 'another argument']] } }) }) ``` -------------------------------- ### Create a Vuex Store Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vuex.md Defines a simple Vuex store with a state and a mutation. This is the store that will be used in the examples. ```js import { createStore } from 'vuex' const store = createStore({ state() { return { count: 0 } }, mutations: { increment(state: any) { state.count += 1 } } }) ``` -------------------------------- ### findComponent Examples Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Demonstrates various ways to use findComponent to locate component instances using query selectors, component names, refs, and direct component imports. ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' import Foo from '@/Foo.vue' test('findComponent', () => { const wrapper = mount(Component) // All the following queries would return a VueWrapper wrapper.findComponent('.foo') wrapper.findComponent('[data-test="foo"]') wrapper.findComponent({ name: 'Foo' }) wrapper.findComponent({ ref: 'foo' }) wrapper.findComponent(Foo) }) ``` -------------------------------- ### Define Components for Stubbing Example Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/stubs-shallow-mount.md Defines the `FetchDataFromApi` and `App` components. `FetchDataFromApi` simulates an API call, while `App` renders a message and `FetchDataFromApi`. ```javascript const FetchDataFromApi = { name: 'FetchDataFromApi', template: `
{{ result }}
`, async mounted() { const res = await axios.get('/api/info') this.result = res.data }, data() { return { result: '' } } } const App = { components: { FetchDataFromApi }, template: `

Welcome to Vue.js 3

` } ``` -------------------------------- ### Asserting Element Existence with get() Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/essentials/conditional-rendering.md Use `wrapper.get()` to find an element and implicitly assert its existence. If the element is not found, `get()` will throw an error. ```javascript test('renders a profile link', () => { const wrapper = mount(Nav) // Here we are implicitly asserting that the // element #profile exists. const profileLink = wrapper.get('#profile') expect(profileLink.text()).toEqual('My Profile') }) ``` -------------------------------- ### Install Vue Test Utils with npm Source: https://github.com/vuejs/test-utils/blob/main/README.md Use this command to add Vue Test Utils as a development dependency using npm. ```bash npm install @vue/test-utils --save-dev ``` -------------------------------- ### Mount and Test a Vue Component Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/index.md Mount a Vue component and assert its rendered output. This example requires importing the `mount` function from `@vue/test-utils`. ```javascript import { mount } from '@vue/test-utils' // The component to test const MessageComponent = { template: '

{{ msg }}

', props: ['msg'] } test('displays message', () => { const wrapper = mount(MessageComponent, { props: { msg: 'Hello world' } }) // Assert the rendered text of the component expect(wrapper.text()).toContain('Hello world') }) ``` -------------------------------- ### Install Vue Test Utils with Yarn Source: https://github.com/vuejs/test-utils/blob/main/README.md Use this command to add Vue Test Utils as a development dependency using Yarn. ```bash yarn add @vue/test-utils --dev ``` -------------------------------- ### Using a Real Router with Composition API Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vue-router.md This example demonstrates how to use a real router instance with the Composition API in tests. It's recommended to create a new router for each test. ```javascript import { mount } from '@vue/test-utils' import { createRouter, createWebHistory } from 'vue-router' import { routes } from '@/router' let router beforeEach(async () => { router = createRouter({ history: createWebHistory(), routes: routes }) router.push('/') await router.isReady() }) test('allows authenticated user to edit a post', async () => { const wrapper = mount(Component, { props: { isAuthenticated: true }, global: { plugins: [router] } }) const push = jest.spyOn(router, 'push') await wrapper.find('button').trigger('click') expect(push).toHaveBeenCalledTimes(1) expect(push).toHaveBeenCalledWith('/posts/1/edit') }) ``` -------------------------------- ### Vue Component Example: Counter.vue Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/essentials/easy-to-test.md A basic Vue component with a counter that increments on button click. This serves as an example for demonstrating testing strategies. ```vue ``` -------------------------------- ### Mounting App with Vue Router Plugin Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vue-router.md Installs Vue Router as a plugin using the `global.plugins` option to resolve component warnings. ```javascript import { mount } from '@vue/test-utils' import { createRouter, createWebHistory } from 'vue-router' import { routes } from '@/router' // This import should point to your routes file declared above const router = createRouter({ history: createWebHistory(), routes: routes }) test('routing', () => { const wrapper = mount(App, { global: { plugins: [router] } }) expect(wrapper.html()).toContain('Welcome to the blogging app') }) ``` -------------------------------- ### Providing Data for Setup/Inject Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Use `global.provide` to make data available to components using Vue's `inject` API within their `setup` function. This is useful for testing components that rely on context provided higher up in the component tree. ```javascript import { mount } from '@vue/test-utils' import Component from './Component.vue' test('global.provide', () => { const wrapper = mount(Component, { global: { provide: { Theme: 'dark' } } }) console.log(wrapper.html()) //=>
Theme is dark
}) ``` ```javascript import { mount } from '@vue/test-utils' import Component from './Component.vue' const ThemeSymbol = Symbol() mount(Component, { global: { provide: { [ThemeSymbol]: 'value' } } }) ``` -------------------------------- ### Mount Component with Real Vuex Store Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vuex.md Mounts the Vue component and installs the Vuex store using `global.plugins`. This allows the component to interact with a real store. ```js import { createStore } from 'vuex' const store = createStore({ state() { return { count: 0 } }, mutations: { increment(state: any) { state.count += 1 } } }) test('vuex', async () => { const wrapper = mount(App, { global: { plugins: [store] } }) await wrapper.find('button').trigger('click') expect(wrapper.html()).toContain('Count: 1') }) ``` -------------------------------- ### Create a Basic Wrapper Plugin Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/extending-vtu/plugins.md A basic plugin is a function that receives the wrapper instance and returns an object with properties to add to the wrapper. This example adds a simple alias. ```javascript // setup.js import { config } from '@vue/test-utils' const myAliasPlugin = wrapper => { return { $el: wrapper.element // simple aliases } } // Call install on the type you want to extend // You can write a plugin for any value inside of config.plugins config.plugins.VueWrapper.install(myAliasPlugin) ``` -------------------------------- ### Test Setup with Teleport Target Creation and Cleanup Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/teleport.md Configures the test environment by creating a DOM element with the ID 'modal' before each test and cleaning up the DOM after each test. This prevents 'Failed to locate Teleport target' warnings. ```typescript import { mount } from '@vue/test-utils' import Navbar from './Navbar.vue' import Signup from './Signup.vue' beforeEach(() => { // create teleport target const el = document.createElement('div') el.id = 'modal' document.body.appendChild(el) }) afterEach(() => { // clean up document.body.innerHTML = '' }) test('teleport', async () => { const wrapper = mount(Navbar) }) ``` -------------------------------- ### Vue Component for Form Handling Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/essentials/forms.md A basic Vue 3 component using ` ``` -------------------------------- ### Mocking Vue Router for Composition API Tests Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vue-router.md This setup mocks the 'vue-router' module to provide mock implementations for `useRouter` and `useRoute`. Use this when you want to isolate component logic from the actual router. ```javascript import { useRouter, useRoute } from 'vue-router' jest.mock('vue-router', () => ({ useRoute: jest.fn(), useRouter: jest.fn(() => ({ push: () => {} })) })) test('allows authenticated user to edit a post', () => { useRoute.mockImplementationOnce(() => ({ params: { id: 1 } })) const push = jest.fn() useRouter.mockImplementationOnce(() => ({ push })) const wrapper = mount(Component, { props: { isAuthenticated: true }, global: { stubs: ["router-link", "router-view"], // Stubs for router-link and router-view in case they're rendered in your template } }) await wrapper.find('button').trigger('click') expect(push).toHaveBeenCalledTimes(1) expect(push).toHaveBeenCalledWith('/posts/1/edit') }) test('redirect an unauthenticated user to 404', () => { useRoute.mockImplementationOnce(() => ({ params: { id: 1 } })) const push = jest.fn() useRouter.mockImplementationOnce(() => ({ push })) const wrapper = mount(Component, { props: { isAuthenticated: false } global: { stubs: ["router-link", "router-view"], // Stubs for router-link and router-view in case they're rendered in your template } }) await wrapper.find('button').trigger('click') expect(push).toHaveBeenCalledTimes(1) expect(push).toHaveBeenCalledWith('/404') }) ``` -------------------------------- ### Test a complex composable with lifecycle hooks Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/reusability-composition.md For composables using lifecycle hooks like onMounted or provide/inject, create a test helper component. This example tests a composable that fetches user data on mount. ```typescript export function useUser(userId) { const user = ref() function fetchUser(id) { axios.get(`users/${id}`).then(response => (user.value = response.data)) } onMounted(() => fetchUser(userId)) return { user } } ``` ```typescript // Mock API request jest.spyOn(axios, 'get').mockResolvedValue({ data: { id: 1, name: 'User' } }) test('fetch user on mount', async () => { const TestComponent = defineComponent({ props: { // Define props, to test the composable with different input arguments userId: { type: Number, required: true } }, setup(props) { return { // Call the composable and expose all return values into our // component instance so we can access them with wrapper.vm ...useUser(props.userId) } } }) const wrapper = mount(TestComponent, { props: { userId: 1 } }) expect(wrapper.vm.user).toBeUndefined() await flushPromises() expect(wrapper.vm.user).toEqual({ id: 1, name: 'User' }) }) ``` -------------------------------- ### Build Documentation Source: https://github.com/vuejs/test-utils/blob/main/README.md Execute this command to build the static documentation files. ```bash pnpm docs:build ``` -------------------------------- ### Get Formatted and Raw HTML of a Component Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Use the `html()` method to get the rendered HTML of a component. Pass `{ raw: true }` to get the unformatted string. ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' test('html', () => { const wrapper = mount(Component) expect(wrapper.html()).toBe( '
\n' + '

Hello world

\n' + '
' ) expect(wrapper.html({ raw: true })).toBe('

Hello world

') }) ``` -------------------------------- ### Testing Initial Route with Async Navigation Source: https://github.com/vuejs/test-utils/blob/main/docs/zh/guide/advanced/vue-router.md Tests the initial route by pushing to '/' and awaiting `router.isReady()` to ensure the router is ready before mounting the app. ```javascript import { mount } from '@vue/test-utils' import { createRouter, createWebHistory } from 'vue-router' import { routes } from '@/router' const router = createRouter({ history: createWebHistory(), routes: routes }) test('routing', async () => { router.push('/') // After this line, the router is ready await router.isReady() const wrapper = mount(App, { global: { plugins: [router] } }) expect(wrapper.html()).toContain('Welcome to the blogging app') }) ``` -------------------------------- ### Mounting with Props and Plugins Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Shows how to mount a component while providing initial props and global Vue application plugins. ```javascript const wrapper = mount(Component, { props: { msg: 'world' }, global: { plugins: [vuex] } }) ``` -------------------------------- ### Interact with Teleported Component Elements Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/teleport.md After getting the teleported component's wrapper with `getComponent`, you can use methods like `get`, `find`, and `trigger` to interact with its elements. ```ts test('teleport', async () => { const wrapper = mount(Navbar) const signup = wrapper.getComponent(Signup) await signup.get('input').setValue('valid_username') await signup.get('form').trigger('submit.prevent') expect(signup.emitted().signup[0]).toEqual(['valid_username']) }) ``` -------------------------------- ### Testing Initial Navigation with `isReady` Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vue-router.md Ensures the initial navigation is complete by awaiting `router.isReady()` before mounting the app. ```javascript import { mount } from '@vue/test-utils' import { createRouter, createWebHistory } from 'vue-router' import { routes } from '@/router' const router = createRouter({ history: createWebHistory(), routes: routes }) test('routing', async () => { router.push('/') // After this line, router is ready await router.isReady() const wrapper = mount(App, { global: { plugins: [router] } }) expect(wrapper.html()).toContain('Welcome to the blogging app') }) ``` -------------------------------- ### Setting up Router Instance Before Each Test Source: https://github.com/vuejs/test-utils/blob/main/docs/zh/guide/advanced/vue-router.md Demonstrates how to create a new Vue Router instance before each test using `beforeEach` to ensure test isolation. ```javascript import { mount, flushPromises } from '@vue/test-utils' import { createRouter, createWebHistory } from 'vue-router' import { routes } from '@/router' let router beforeEach(async () => { router = createRouter({ history: createWebHistory(), routes: routes }) }) test('routing', async () => { ``` -------------------------------- ### Get an element by selector Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Use `get` to retrieve a specific DOM element. It returns a `DOMWrapper` if found, otherwise it throws an error. Use this when you expect an element to exist. ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' test('get', () => { const wrapper = mount(Component) wrapper.get('span') //=> found; returns DOMWrapper expect(() => wrapper.get('.not-there')).toThrowError() }) ``` -------------------------------- ### Vuex Composition API `useStore` with Injection Key Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vuex.md Demonstrates using `useStore` with a unique injection key for the Composition API. ```javascript import { createStore } from 'vuex' import { createApp } from 'vue' // create a globally unique symbol for the injection key const key = Symbol() const App = { setup() { // use unique key to access store const store = useStore(key) } } const store = createStore({ /* ... */ }) const app = createApp({ /* ... */ }) // specify key as second argument when calling app.use(store) app.use(store, key) ``` -------------------------------- ### Basic Component Mounting Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Demonstrates the basic usage of the `mount` function to render a simple Vue component and assert its HTML content. ```javascript import { mount } from '@vue/test-utils' const Component = { template: '
Hello world
' } test('mounts a component', () => { const wrapper = mount(Component, {}) expect(wrapper.html()).toContain('Hello world') }) ``` -------------------------------- ### attributes Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Returns attributes on a DOM node. It can be used to get all attributes or a specific attribute by its key. ```APIDOC ## attributes ### Description Returns attributes on a DOM node. ### Signature ```ts attributes(): { [key: string]: string } attributes(key: string): string attributes(key?: string): { [key: string]: string } | string ``` ### Details `Component.vue`: ```vue ``` `Component.spec.js`: ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' test('attributes', () => { const wrapper = mount(Component) expect(wrapper.attributes('id')).toBe('foo') expect(wrapper.attributes('class')).toBe('bar') }) ``` ``` -------------------------------- ### props() Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Returns props passed to a Vue Component. Can be used to get all props or a specific prop by its selector. ```APIDOC ## props(selector?: string) ### Description Returns props passed to a Vue Component. Can be used to get all props or a specific prop by its selector. ### Method N/A (Method of a wrapper object) ### Parameters #### Path Parameters - **selector** (string) - Optional - The name of the prop to retrieve. ### Response - **{ [key: string]: any } | any** - An object containing all props, or the value of a specific prop if a selector is provided. ``` -------------------------------- ### Checkout and Tag for Release Source: https://github.com/vuejs/test-utils/blob/main/README.md Commands to prepare for a release by checking out the main branch, pulling the latest changes, and creating a version tag. ```bash git checkout main git pull git tag v2.x.y git push origin v2.x.y ``` -------------------------------- ### Vue Counter Component Example Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/async-suspense.md A basic Vue component that displays a count and increments it when a button is clicked. ```javascript const Counter = { template: `

Count: {{ count }}

`, data() { return { count: 0 } }, methods: { handleClick() { this.count += 1 } } } ``` -------------------------------- ### Get Emitted Events from a Component Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Retrieve all emitted events and their arguments from a component. Arguments are stored in an array for each event. ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' test('emitted', () => { const wrapper = mount(Component) // wrapper.emitted() equals to { greet: [ ['hello'], ['goodbye'] ] } expect(wrapper.emitted()).toHaveProperty('greet') expect(wrapper.emitted().greet).toHaveLength(2) expect(wrapper.emitted().greet[0]).toEqual(['hello']) expect(wrapper.emitted().greet[1]).toEqual(['goodbye']) }) ``` -------------------------------- ### Get Classes of a DOM Element Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Returns an array of classes on an element, or a boolean indicating if a specific class exists. ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' test('classes', () => { const wrapper = mount(Component) expect(wrapper.classes()).toContain('my-span') expect(wrapper.classes('my-span')).toBe(true) expect(wrapper.classes('not-existing')).toBe(false) }) ``` -------------------------------- ### Get Attributes of a DOM Element Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Retrieve attributes from a DOM element using its key or all attributes if no key is provided. ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' test('attributes', () => { const wrapper = mount(Component) expect(wrapper.attributes('id')).toBe('foo') expect(wrapper.attributes('class')).toBe('bar') }) ``` -------------------------------- ### Provide Keyed `useStore` using `global.provide` Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vuex.md Injects the Vuex store using a specific injection key via the `global.provide` mounting option. ```javascript // app.spec.js import { createStore } from 'vuex' import { key } from './store' const store = createStore({ /* ... */ }) const wrapper = mount(App, { global: { provide: { [key]: store } } }) ``` -------------------------------- ### Create Vuex Store with Initial State Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vuex.md Wraps `createStore` to allow seeding the initial state, useful for testing specific scenarios. ```javascript const createVuexStore = initialState => createStore({ state: { count: 0, ...initialState }, mutations: { increment(state, value = 1) { state.count += value } } }) ``` -------------------------------- ### Get Teleported Component Instance Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/teleport.md Use `getComponent` to retrieve a wrapper for a component that has been teleported. This operates on the Virtual DOM, not the regular DOM. ```ts beforeEach(() => { // ... }) afterEach(() => { // ... }) test('teleport', async () => { const wrapper = mount(Navbar) wrapper.getComponent(Signup) // got it! }) ``` -------------------------------- ### Mocking Dates and Timers with Vitest Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/faq/index.md When mocking system time with Vitest, ensure components are mounted after calling `vi.setSystemTime`. Mounting before may lead to reactivity issues. ```javascript vi.setSystemTime(new Date(2024, 1, 1)) ``` -------------------------------- ### Define an App Component Using CustomButton Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/stubs-shallow-mount.md This is an example of a parent component that uses the CustomButton and conditionally renders content within its slot. ```javascript const App = { props: ['authenticated'], components: { CustomButton }, template: `
Log out
Log in
` } ``` -------------------------------- ### Testing Show Component with `setProps` Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/essentials/passing-data.md Tests the Show component by mounting it and then using `setProps` to change the `show` prop, verifying that the greeting is hidden. ```js import { mount } from '@vue/test-utils' import Show from './Show.vue' test('renders a greeting when show is true', async () => { const wrapper = mount(Show) expect(wrapper.html()).toContain('Hello') await wrapper.setProps({ show: false }) expect(wrapper.html()).not.toContain('Hello') }) ``` -------------------------------- ### Define a Component with a Default Slot Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/slots.md This example shows a basic Vue component template that uses a default slot to render content. ```javascript const Layout = { template: `

Welcome!

Thanks for visiting.
` } ``` -------------------------------- ### Test a simple composable Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/reusability-composition.md Test simple composables directly without needing @vue/test-utils. This example shows testing a counter composable. ```typescript export function useCounter() { const counter = ref(0) function increase() { counter.value += 1 } return { counter, increase } } ``` ```typescript test('increase counter on call', () => { const { counter, increase } = useCounter() expect(counter.value).toBe(0) increase() expect(counter.value).toBe(1) }) ``` -------------------------------- ### Get Component Props Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Retrieve props passed to a Vue component using the `props()` method. It can return all props or a specific prop by its name. ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' test('props', () => { const wrapper = mount(Component, { global: { stubs: ['Foo'] } }) const foo = wrapper.getComponent({ name: 'Foo' }) expect(foo.props('truthy')).toBe(true) expect(foo.props('object')).toEqual({}) expect(foo.props('notExisting')).toEqual(undefined) expect(foo.props()).toEqual({ truthy: true, object: {}, string: 'string' }) }) ``` -------------------------------- ### Provide Unkeyed `useStore` via Global Mount Option Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vuex.md Injects the Vuex store into a component using the `provide` global mounting option when no injection key is used. ```javascript import { createStore } from 'vuex' const store = createStore({ // ... }) const wrapper = mount(App, { global: { provide: { store: store } } }) ``` -------------------------------- ### get Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Retrieves a DOM element by its selector and returns a `DOMWrapper`. If the element is not found, it throws an error. This method is recommended for asserting the existence of an element. ```APIDOC ## get ### Description Gets an element by its selector and returns a `DOMWrapper` if found. Throws an error if the element is not found. It is similar to `find`, but `get` throws an error if an element is not found while `find` will return an `ErrorWrapper`. ### Signature ```ts get(selector: K): Omit, 'exists'> get(selector: K): Omit, 'exists'> get(selector: string): Omit, 'exists'> get(selector: string): Omit, 'exists'> ``` ### Usage As a rule of thumb, always use `get` except when you are asserting something doesn't exist. In that case use `find`. ``` -------------------------------- ### Define Components for Shallow Mount with Exception Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/stubs-shallow-mount.md Defines `ComplexA`, `ComplexB`, `ComplexC`, and `ComplexComponent`. `ComplexComponent` uses the other three components, setting up a scenario for selective stubbing. ```javascript const ComplexA = { template: '

Hello from real component!

' } const ComplexComponent = { components: { ComplexA, ComplexB, ComplexC }, template: `

Welcome to Vue.js 3

` } ``` -------------------------------- ### Find all matching components Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Use `findAllComponents` to find all component instances that match the provided selector. Note that `ref` syntax is not supported. ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' test('findAllComponents', () => { const wrapper = mount(Component) // Returns an array of VueWrapper wrapper.findAllComponents('[data-test="number"]') }) ``` -------------------------------- ### Define a Component with Named Slots Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/slots.md This example demonstrates a Vue component template with multiple named slots for header, main, and footer content. ```javascript const Layout = { template: `
` } ``` -------------------------------- ### Basic App Structure with Vue Router Links Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vue-router.md Defines the main application template with a link to the posts route and a router view. ```javascript const App = { template: ` Go to posts ` } const Posts = { template: `

Posts

  • {{ post.name }}
`, data() { return { posts: [{ id: 1, name: 'Testing Vue Router' }] } } } ``` -------------------------------- ### Get Text Content of an Element Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md The text() method retrieves the text content of a DOM element. It is useful for asserting the rendered text within components. ```vue ``` ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' test('text', () => { const wrapper = mount(Component) expect(wrapper.find('p').text()).toBe('Hello world') }) ``` -------------------------------- ### Testing Password Component with Mounting Options Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/essentials/passing-data.md Tests the Password component by mounting it with specific `props` and `data` options to simulate a short password and verify the error message. ```js test('renders an error if length is too short', () => { const wrapper = mount(Password, { props: { minLength: 10 }, data() { return { password: 'short' } } }) expect(wrapper.html()).toContain('Password must be at least 10 characters') }) ``` -------------------------------- ### Vue Router Configuration Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vue-router.md Sets up Vue Router with web history and defines the application routes. ```javascript import { createRouter, createWebHistory } from 'vue-router' const routes = [ { path: '/', component: { template: 'Welcome to the blogging app' } }, { path: '/posts', component: Posts } ] const router = createRouter({ history: createWebHistory(), routes: routes }) export { routes } export default router ``` -------------------------------- ### Kebab-case Component Stubs in shallowMount Source: https://github.com/vuejs/test-utils/blob/main/docs/migration/index.md Before Vue 3, `shallowMount` used kebab-case for component stubs by default. This example shows the change in how to find a component stub. ```javascript import { shallowMount } from '@vue/test-utils' import App from '@/App.vue' describe('App.vue', () => { it('finds the helloworld component', () => { const wrapper = shallowMount(App, {}) const componentStub = wrapper.find('helloworld-stub'); expect(componentStub.html()).toBeTruthy(); }) }) ``` ```javascript import { shallowMount } from '@vue/test-utils' import App from '@/App.vue' describe('App.vue', () => { it('finds the helloworld component', () => { const wrapper = shallowMount(App, {}) const componentStub = wrapper.find('hello-world-stub'); expect(componentStub.html()).toBeTruthy(); }) }) ``` -------------------------------- ### config.global Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Allows configuring global mounting options for your entire test suite. These options are applied by default to all component mounts and can be overridden on a per-test basis. ```APIDOC ## config.global ### Description Instead of configuring mounting options on a per-test basis, you can configure them for your entire test suite. These will be used by default every time you `mount` a component. If desired, you can then override your defaults on a per-test basis. ### Type Definition ```ts type GlobalMountOptions = { plugins?: (Plugin | [Plugin, ...any[]])[] config?: Partial> mixins?: ComponentOptions[] mocks?: Record provide?: Record components?: Record directives?: Record stubs?: Stubs = Record | Array renderStubDefaultSlot?: boolean } ``` ### Example An example might be globally mocking the `$t` variable from vue-i18n and a component: `Component.vue`: ```vue ``` `Component.spec.js`: ```js {1,8-10,12-14} import { config, mount } from '@vue/test-utils' import { defineComponent } from 'vue' const MyComponent = defineComponent({ template: `
My component
` }) config.global.stubs = { MyComponent } config.global.mocks = { $t: (text) => text } test('config.global mocks and stubs', () => { const wrapper = mount(Component) expect(wrapper.html()).toBe('

message

My component
') }) ``` ::: tip Remember that this behavior is global, not on a mount by mount basis. You might need to enable/disable it before and after each test. ::: ``` -------------------------------- ### Initial Test Without Vue Router Plugin Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vue-router.md A minimal test case that fails due to missing Vue Router components. ```javascript import { mount } from '@vue/test-utils' test('routing', () => { const wrapper = mount(App) expect(wrapper.html()).toContain('Welcome to the blogging app') }) ``` -------------------------------- ### Asserting Element Non-Existence with find().exists() Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/essentials/conditional-rendering.md Use `wrapper.find().exists()` to assert that an element does not exist in the DOM. Using `get()` for non-existent elements will cause the test to fail. ```javascript test('does not render an admin link', () => { const wrapper = mount(Nav) // Using `wrapper.get` would throw and make the test fail. expect(wrapper.find('#admin').exists()).toBe(false) }) ``` -------------------------------- ### Mount Component with Mock Vuex Store Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/vuex.md Mounts the Vue component and provides a mock Vuex store using `global.mocks`. This is useful for unit testing components in isolation. ```js test('vuex using a mock store', async () => { const $store = { state: { count: 25 }, commit: jest.fn() } const wrapper = mount(App, { global: { mocks: { $store } } }) expect(wrapper.html()).toContain('Count: 25') await wrapper.find('button').trigger('click') expect($store.commit).toHaveBeenCalled() }) ``` -------------------------------- ### Define Custom Wrapper Types with TypeScript Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/extending-vtu/plugins.md To use custom wrapper plugins with TypeScript, declare your custom wrapper function in a `vue-test-utils.d.ts` file. This example adds the `findByTestId` method signature. ```typescript import { DOMWrapper } from '@vue/test-utils' declare module '@vue/test-utils' { interface VueWrapper { findByTestId(testId: string): DOMWrapper[] } } ``` -------------------------------- ### mount Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Creates a Wrapper that contains the mounted and rendered Vue component to test. It's the main method exposed by Vue Test Utils for creating a Vue 3 app that holds and renders the Component under testing, returning a wrapper to interact with the component. ```APIDOC ## mount ### Description Creates a Wrapper that contains the mounted and rendered Vue component to test. Note that when mocking dates/timers with Vitest, this must be called after `vi.setSystemTime`. `mount` is the main method exposed by Vue Test Utils. It creates a Vue 3 app that holds and renders the Component under testing. In return, it creates a wrapper to act and assert against the Component. ### Method mount ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters (MountingOptions) #### `attachTo` Specify the node to mount the component on. This is not available when using `renderToString`. Can be a valid CSS selector, or an [`Element`](https://developer.mozilla.org/en-US/docs/Web/API/Element) connected to the document. #### `attrs` Sets HTML attributes to component. Can be a `Record`. #### `data` Overrides a component's default `data`. Must be a function. #### `props` Props to pass to the component. Can be a `(RawProps & Props) | ({} extends Props ? null : never)`. #### `slots` Slots to pass to the component. Can be `{ [key: string]: Slot } & { default?: Slot }`. #### `global` Configure the Vue 3 app by the [`MountingOptions.global` config property](#global). This would be useful for providing mocked values which your components expect to have available. #### `shallow` If true, the component will be mounted in a shallow manner. ### Request Example ```js import { mount } from '@vue/test-utils' const Component = { template: '
Hello world
' } test('mounts a component', () => { const wrapper = mount(Component, {}) expect(wrapper.html()).toContain('Hello world') }) ``` ### Response #### Success Response - **VueWrapper** - A wrapper object that contains the mounted and rendered Vue component. ``` -------------------------------- ### Testing Implementation Details: Counter Component Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/essentials/easy-to-test.md An example test that relies on implementation details like internal data (`count`) and CSS classes (`.paragraph`). This test is prone to breaking on refactors. ```js import { mount } from '@vue/test-utils' import Counter from './Counter.vue' test('counter text updates', async () => { const wrapper = mount(Counter) const paragraph = wrapper.find('.paragraph') expect(paragraph.text()).toBe('Times clicked: 0') await wrapper.setData({ count: 2 }) expect(paragraph.text()).toBe('Times clicked: 2') }) ``` -------------------------------- ### global.renderStubDefaultSlot Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Renders the default slot content, even when using shallow mounting. ```APIDOC ## global.renderStubDefaultSlot ### Description Renders the `default` slot content, even when using `shallow` or `shallowMount`. ### Signature ```ts renderStubDefaultSlot?: boolean ``` ### Details Defaults to **false**. ::: warning Due to technical limitations, **this behavior cannot be extended to slots other than the default one**. ::: ### Example ```js import { mount } from '@vue/test-utils' import Component from './Component.vue' test('global.renderStubDefaultSlot', () => { const wrapper = mount(ComponentWithSlots, { slots: { default: '
My slot content
' }, shallow: true, global: { renderStubDefaultSlot: true } }) expect(wrapper.html()).toBe( '
My slot content
' ) }) ``` ``` -------------------------------- ### Create a Todo Item Test Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/essentials/a-crash-course.md Demonstrates creating a todo item by simulating user input and form submission, then asserting the expected DOM state. Requires mounting the component and interacting with elements. ```javascript import { mount } from '@vue/test-utils' import TodoApp from './TodoApp.vue' test('creates a todo', async () => { const wrapper = mount(TodoApp) await wrapper.get('[data-test="new-todo"]').setValue('New todo') await wrapper.get('[data-test="form"]').trigger('submit') expect(wrapper.findAll('[data-test="todo"]')).toHaveLength(2) }) ``` -------------------------------- ### Stubbing RouterLink Component Source: https://github.com/vuejs/test-utils/blob/main/docs/api/index.md Use RouterLinkStub in the global stubs option when mounting a component to replace the actual router-link. This is useful for testing components that use router-link without needing a full router setup. ```javascript import { mount, RouterLinkStub } from '@vue/test-utils' const wrapper = mount(Component, { global: { stubs: { RouterLink: RouterLinkStub, }, }, }) expect(wrapper.findComponent(RouterLinkStub).props().to).toBe('/some/path') ``` -------------------------------- ### Test Default Slot Content Source: https://github.com/vuejs/test-utils/blob/main/docs/guide/advanced/slots.md Use the `slots` mounting option to pass text content to the default slot and verify its rendering. ```javascript test('layout default slot', () => { const wrapper = mount(Layout, { slots: { default: 'Main Content' } }) expect(wrapper.html()).toContain('Main Content') }) ```