Skip to main content
Cypress App

Vue Examples

To mount a component with cy.mount(), import the component and pass it to the method:

import { Stepper } from './Stepper.vue'

it('mounts', () => {
cy.mount(Stepper)
})

Passing Data to a Component​

You can pass props and events to a component by setting props in the options:

cy.mount(Stepper, {
props: {
initial: 100,
},
})

Testing Event Handlers​

Pass a Cypress spy to an event prop and validate it was called:

it('clicking + fires a change event with the incremented value', () => {
const onChangeSpy = cy.spy().as('onChangeSpy')
cy.mount(Stepper, { props: { onChange: onChangeSpy } })
cy.get('[data-cy=increment]').click()
cy.get('@onChangeSpy').should('have.been.calledWith', 1)
})

Using JSX​

The mount command also supports JSX syntax (provided that you've configured your bundler to support transpiling JSX or TSX files). Some might find using JSX syntax beneficial when writing tests.

Sample with JSX:

it('clicking + fires a change event with the incremented value', () => {
const onChangeSpy = cy.spy().as('onChangeSpy')
cy.mount(<Stepper initial={100} onChange={onChangeSpy} />)
cy.get('[data-cy=increment]').click()
cy.get('@onChangeSpy').should('have.been.calledWith', 101)
})

Testing Error States​

cy.mount() is an asynchronous Cypress command: it enqueues the mount and returns immediately, before the component ever renders. When a component throws during render, the error surfaces as an uncaught exception rather than as a synchronous throw.

By default Cypress fails the test on any uncaught exception, so to assert on a render error you listen for it with cy.on('uncaught:exception') and return false to prevent Cypress from failing the test:

import UserProfile from './UserProfile.vue'

it('surfaces a render error', () => {
cy.on('uncaught:exception', (err) => {
// Assert on the error thrown during render...
expect(err.message).to.include('user is required')

// ...and return false so Cypress does not fail the test.
return false
})

cy.mount(UserProfile)
})

Testing with onErrorCaptured​

The recommended way to render fallback UI in Vue is a wrapper component that uses the onErrorCaptured lifecycle hook to catch errors from its descendants. You can mount a component inside such a wrapper and assert that the wrapper displays the fallback UI:

// ErrorBoundary.cy.js
import { h } from 'vue'
import ErrorBoundary from './ErrorBoundary.vue'
import ChildWithError from './ChildWithError.vue'

it('displays the fallback UI on error', () => {
// onErrorCaptured renders fallback UI, but it does NOT stop the error from
// propagating to Cypress as an uncaught exception. Cypress fails on uncaught
// exceptions by default, so we must still suppress that behavior.
cy.on('uncaught:exception', (err) => {
// Only suppress the specific error we expect.
expect(err.message).to.include('I crashed!')

return false
})

cy.mount(() => h(ErrorBoundary, () => h(ChildWithError)))

cy.get('[data-cy=fallback]').should('contain', 'Something went wrong.')
})

Where ErrorBoundary captures the error with onErrorCaptured and renders fallback UI:

<!-- ErrorBoundary.vue -->
<template>
<div v-if="error" data-cy="fallback">Something went wrong.</div>
<slot v-else />
</template>

<script setup>
import { ref, onErrorCaptured } from 'vue'

const error = ref(null)

onErrorCaptured((err) => {
error.value = err

// Returning false stops the error from propagating further up the Vue tree,
// but it still reaches Cypress as an uncaught exception.
return false
})
</script>

Using Slots​

Default Slot​

import DefaultSlot from './DefaultSlot.vue'

describe('<DefaultSlot />', () => {
it('renders', () => {
cy.mount(DefaultSlot, {
slots: {
default: 'Hello there!',
},
})
cy.get('div.content').should('have.text', 'Hello there!')
})
})

Named Slot​

import NamedSlot from './NamedSlot.vue'

describe('<NamedSlot />', () => {
it('renders', () => {
const slots = {
header: 'my header',
footer: 'my footer',
}
cy.mount(NamedSlot, {
slots,
})
cy.get('header').should('have.text', 'my header')
cy.get('footer').should('have.text', 'my footer')
})
})

For more info on testing Vue components with slots, refer to the Vue Test Utils Slots guide.

Using Vue Test Utils​

To encourage interoperability between your existing component tests and Cypress, we support using Vue Test Utils' API.

cy.mount(Stepper).then(({ wrapper, component }) => {
// `wrapper` is the Vue Test Utils wrapper
// `component` is the component instance itself
})

If you intend to use the wrapper frequently and use Vue Test Util's API, we recommend you write a custom mount command and create a Cypress alias to get back at the wrapper.

import { mount } from 'cypress/vue'

Cypress.Commands.add('mount', (...args) => {
return mount(...args).then(({ wrapper }) => {
return cy.wrap(wrapper).as('vue')
})
})
// the "@vue" alias will now work anywhere
// after you've mounted your component
cy.mount(Stepper).doStuff().get('@vue') // The subject is now the Vue Wrapper

The @vue alias means that you are able to get to the resulting wrapper returned from the mount command and use wrapper.emitted() to gain access to Native DOM events that fired, as well as custom events that your component under test emitted.

Because wrapper.emitted() is only data, and NOT spy-based you have to unpack its results to write assertions.

Your test failure messages are not as helpful because you're not able to use the Sinon-Chai library that Cypress ships, which comes with methods such as to.have.been.called and to.have.been.calledWith.

Usage of the cy.get('@vue') alias may look something like the below code snippet.

Notice that we're using the 'should' function signature to take advantage of Cypress's retryability. If we chained using cy.then instead of cy.should, we may run into the kinds of issues you have in Vue Test Utils tests where you have to use await frequently to make sure the DOM has updated or any reactive events have fired.

cy.mount(Stepper, { props: { initial: 100 } })
cy.get(incrementSelector).click()
cy.get('@vue').should(({ wrapper }) => {
expect(wrapper.emitted('change')).to.have.length
expect(wrapper.emitted('change')[0][0]).to.equal('101')
})

Regardless of our recommendation to use spies instead of the internal Vue Test Utils API, you may decide to continue using emitted as it automatically records every single event emitted from the component, and so you don't have to create a spy for every event emitted.

This auto-spying behavior could be useful for components that emit many custom events.

Mount Storybook stories in Vue component tests​

Component tests can reuse the Storybook stories you already write. A story sets up the component with the args and decorators that make it render, so the test starts from a working state and goes straight to the assertions.

Storybook's portable stories API does the work, so Cypress needs no plugin. composeStories() from @storybook/vue3 turns each story in a CSF file into a component with the story's args and decorators applied, and cy.mount() accepts that component like any other.

Given this component and its stories:

src/components/Button.vue
<script setup>
defineProps({ label: String, primary: Boolean, theme: String })
defineEmits(['click'])
</script>

<template>
<button :class="{ primary }" :data-theme="theme" @click="$emit('click')">
{{ label }}
</button>
</template>
src/components/Button.stories.js
import Button from './Button.vue'

export default {
component: Button,
args: { label: 'Button' },
decorators: [() => ({ template: '<div class="padded"><story /></div>' })],
}

export const Primary = {
args: { primary: true, label: 'Primary' },
}

export const Secondary = {
args: { label: 'Secondary' },
}

Compose the stories once at the top of the spec, then mount each one. Props passed to cy.mount() override the story's args:

src/components/Button.cy.js
import { composeStories } from '@storybook/vue3'
import * as stories from './Button.stories'

const { Primary, Secondary } = composeStories(stories)

it('renders the Primary story', () => {
cy.mount(Primary)
cy.get('.padded button')
.should('have.text', 'Primary')
.and('have.class', 'primary')
})

it('overrides story args with props', () => {
cy.mount(Secondary, { props: { label: 'Save' } })
cy.get('button').should('have.text', 'Save')
})

Apply Storybook preview settings in component tests​

Global decorators and args in .storybook/preview apply only when you pass them to setProjectAnnotations(). Call it once in the component support file, next to the code that registers cy.mount(), and every composed story picks them up:

cypress/support/component.js
import { setProjectAnnotations } from '@storybook/vue3'
import { mount } from 'cypress/vue'
import * as previewAnnotations from '../../.storybook/preview'

setProjectAnnotations(previewAnnotations)

Cypress.Commands.add('mount', mount)

Compile Storybook template decorators in Cypress​

A decorator written as a template string, like the one in Button.stories.js, needs the build of Vue that includes the template compiler. Without it, the story renders nothing and Vue logs Component provided template option but runtime compilation is not supported in this build of Vue. Alias vue to vue/dist/vue.esm-bundler.js in the Vite config Cypress uses, so the alias applies to your tests and not to your production build.

When viteConfig is set, Cypress uses it in place of your project's vite.config, which drops that file's plugins and aliases. Set configFile inside viteConfig to your config's filename, such as vite.config.ts, so Vite loads it and merges the alias on top:

const { defineConfig } = require('cypress')

module.exports = defineConfig({
component: {
devServer: {
framework: 'vue',
bundler: 'vite',
viteConfig: {
configFile: 'vite.config.js',
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
},
},
},
},
},
})

Decorators written as render functions, such as (story) => () => h('div', { class: 'padded' }, [h(story())]), don't need the alias.

Spy on events from a decorated Storybook story​

Storybook passes the props you give cy.mount() to the story's component as args. A composed story is also a functional component, so Vue passes the event listeners among those props to the outermost element the story renders too. With a decorator, that element is the decorator's wrapper, so a single click on the component reaches the spy twice: once from the component's emitted event and once from the native click on the wrapper. Set inheritAttrs: false on the composed story so the listener reaches only the component.

The setting changes the composed story itself, so every test in the spec that mounts the story gets it. Set it once, right after composeStories(), so the scope is clear at a glance:

src/components/ButtonEvents.cy.js
import { composeStories } from '@storybook/vue3'
import * as stories from './Button.stories'

const { Primary } = composeStories(stories)
Object.assign(Primary, { inheritAttrs: false })

it('emits click', () => {
const onClick = cy.spy().as('onClick')
cy.mount(Primary, { props: { onClick } })
cy.get('button').click()
cy.get('@onClick').should('have.been.calledOnce')
})

Custom Mount Commands​

Customizing cy.mount()​

While you can use the mount() function in your tests, we recommend using cy.mount(), which is a custom command that you define in the cypress/support/component.js file:

import { mount } from 'cypress/vue'

Cypress.Commands.add('mount', mount)

The support file registers cy.mount() for any test without having to import the mount() function in each and every spec file.

By default, cy.mount() is a simple passthrough to mount(), however, you can customize cy.mount() to fit your needs. For instance, if you are using plugins or other global app-level setups in your Vue app, you can configure them here.

Below are a few examples that demonstrate using a custom mount command. You can adjust these examples for most other providers that you need to support.

Replicating Plugins​

Most applications have state management or routing. Both of these are Vue plugins.

import { createPinia } from 'pinia' // or Vuex
import { createI18n } from 'vue-i18n'
import { mount } from 'cypress/vue'
import { h } from 'vue'

// We recommend that you pull this out
// into a constants file that you share with
// your main.js file.
const i18nOptions = {
locale: 'en',
messages: {
en: {
hello: 'hello!',
},
ja: {
hello: 'こんにちは!',
},
},
}

Cypress.Commands.add('mount', (component, ...args) => {
args.global = args.global || {}
args.global.plugins = args.global.plugins || []
args.global.plugins.push(createPinia())
args.global.plugins.push(createI18n())

return mount(
() => {
return h(VApp, {}, component)
},
...args
)
})

Replicating the expected Component Hierarchy​

Some Vue applications, most famously Vue apps built on top of Vuetify, require certain components to be structured in a specific hierarchy.

All Vuetify applications require that you wrap your app in a VApp component when you build it. The VApp wrapper is an implementation detail of Vuetify, but once users try to test components that depend on Vuetify, they get Vuetify-specific compilation errors and quickly find out that they need to replicate that component hierarchy any time they need to mount a component that uses a Vuetify component!

Custom cy.mount commands to the rescue! You may find the JSX syntax to be more straightforward.

You also need to replicate the plugin setup steps from the Vuetify docs for everything to compile.

import Vuetify from 'vuetify/lib'
import { VApp } from 'vuetify'
import { mount } from 'cypress/vue'
import { h } from 'vue'

// We recommend that you pull this out
// into a constants file that you share with
// your main.js file.
const vuetifyOptions = {}

Cypress.Commands.add('mount', (component, ...args) => {
args.global = args.global || {}
args.global.plugins = args.global.plugins || []
args.global.plugins.push(new Vuetify(vuetifyOptions))

return mount(
() => {
return h(VApp, {}, component)
},
...args
)
})

Vue Router​

To use Vue Router, create a command to register the plugin and pass in a custom implementation of the router via the options param.

import { mount } from 'cypress/vue'
import { createMemoryHistory, createRouter } from 'vue-router'
import { routes } from '../../src/router'

Cypress.Commands.add('mount', (component, options = {}) => {
// Setup options object
options.global = options.global || {}
options.global.plugins = options.global.plugins || []

// create router if one is not provided
if (!options.router) {
options.router = createRouter({
routes: routes,
history: createMemoryHistory(),
})
}

// Add router plugin
options.global.plugins.push({
install(app) {
app.use(options.router)
},
})

return mount(component, options)
})

Vuex​

To use a component that uses Vuex, create a mount command that configures a Vuex store for your component.

import { mount } from 'cypress/vue'
import { getStore } from '../../src/plugins/store'

Cypress.Commands.add('mount', (component, options = {}) => {
// Setup options object
options.global = options.global || {}
options.global.stubs = options.global.stubs || {}
options.global.stubs['transition'] = false
options.global.components = options.global.components || {}
options.global.plugins = options.global.plugins || []

// Use store passed in from options, or initialize a new one
const { store = getStore(), ...mountOptions } = options

// Add Vuex plugin
options.global.plugins.push({
install(app) {
app.use(store)
},
})

return mount(component, mountOptions)
})
info

The getStore method is a factory method that initializes Vuex and creates a new store. It is important to initialize the store with each new test to ensure changes to the store don't affect other tests.

Global Components​

If you register components globally in the main application file, set them up in your mount command so your component renders them properly:

import { mount } from 'cypress/vue'
import Button from '../../src/components/Button.vue'

Cypress.Commands.add('mount', (component, options = {}) => {
// Setup options object
options.global = options.global || {}
options.global.components = options.global.components || {}

// Register global components
options.global.components['Button'] = Button

return mount(component, options)
})