You’re browsing the documentation for Vue Test Utils for Vue v2.x and earlier.

To read docs for Vue Test Utils for Vue 3, click here.

API

mount()

  • Arguments:

    • {Component} component
    • {Object} options
  • Returns: {Wrapper}

  • Options:

See options

  • Usage:

Creates a Wrapper that contains the mounted and rendered Vue component.

Without options:

import { mount } from '@vue/test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', () => {
    const wrapper = mount(Foo)
    expect(wrapper.contains('div')).toBe(true)
  })
})

With Vue options:

import { mount } from '@vue/test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', () => {
    const wrapper = mount(Foo, {
      propsData: {
        color: 'red'
      }
    })
    expect(wrapper.props().color).toBe('red')
  })
})

Attach to DOM:

import { mount } from '@vue/test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', () => {
    const div = document.createElement('div')
    document.body.appendChild(div)
    const wrapper = mount(Foo, {
      attachTo: div
    })
    expect(wrapper.contains('div')).toBe(true)
    wrapper.destroy()
  })
})

Default and named slots:

import { mount } from '@vue/test-utils'
import Foo from './Foo.vue'
import Bar from './Bar.vue'
import FooBar from './FooBar.vue'

describe('Foo', () => {
  it('renders a div', () => {
    const wrapper = mount(Foo, {
      slots: {
        default: [Bar, FooBar],
        fooBar: FooBar, // Will match `<slot name="FooBar" />`.
        foo: '<div />'
      }
    })
    expect(wrapper.contains('div')).toBe(true)
  })
})

Stubbing global properties:

import { mount } from '@vue/test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', () => {
    const $route = { path: 'http://www.example-path.com' }
    const wrapper = mount(Foo, {
      mocks: {
        $route
      }
    })
    expect(wrapper.vm.$route.path).toBe($route.path)
  })
})

Stubbing components:

import { mount } from '@vue/test-utils'
import Foo from './Foo.vue'
import Bar from './Bar.vue'
import Faz from './Faz.vue'

describe('Foo', () => {
  it('renders a div', () => {
    const wrapper = mount(Foo, {
      stubs: {
        BarFoo: true,
        FooBar: Faz,
        Bar: { template: '<div class="stubbed" />' }
      }
    })
    expect(wrapper.contains('.stubbed')).toBe(true)
    expect(wrapper.contains(Bar)).toBe(true)
  })
})

Deprecation Notice:

When stubbing components, supplying a string (ComponentToStub: '<div class="stubbed" />) is no longer supported.

shallowMount()

  • Arguments:

    • {Component} component
    • {Object} options
      • {HTMLElement|string} string
      • {boolean} attachToDocument
      • {Object} context
        • {Array<Component|Object>|Component} children
      • {Object} slots
        • {Array<Component|Object>|Component|String} default
        • {Array<Component|Object>|Component|String} named
      • {Object} mocks
      • {Object|Array<string>} stubs
      • {Vue} localVue
  • Returns: {Wrapper}

  • Options:

See options

  • Usage:

Like mount, it creates a Wrapper that contains the mounted and rendered Vue component, but with stubbed child components.

Without options:

import { shallowMount } from '@vue/test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', () => {
    const wrapper = shallowMount(Foo)
    expect(wrapper.contains('div')).toBe(true)
  })
})

With Vue options:

import { shallowMount } from '@vue/test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', () => {
    const wrapper = shallowMount(Foo, {
      propsData: {
        color: 'red'
      }
    })
    expect(wrapper.props().color).toBe('red')
  })
})

Attach to DOM:

import { shallowMount } from '@vue/test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', () => {
    const div = document.createElement('div')
    document.body.appendChild(div)
    const wrapper = shallowMount(Foo, {
      attachTo: div
    })
    expect(wrapper.contains('div')).toBe(true)
    wrapper.destroy()
  })
})

Default and named slots:

import { shallowMount } from '@vue/test-utils'
import Foo from './Foo.vue'
import Bar from './Bar.vue'
import FooBar from './FooBar.vue'

describe('Foo', () => {
  it('renders a div', () => {
    const wrapper = shallowMount(Foo, {
      slots: {
        default: [Bar, FooBar],
        fooBar: FooBar, // Will match <slot name="FooBar" />,
        foo: '<div />'
      }
    })
    expect(wrapper.contains('div')).toBe(true)
  })
})

Stubbing global properties:

import { shallowMount } from '@vue/test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', () => {
    const $route = { path: 'http://www.example-path.com' }
    const wrapper = shallowMount(Foo, {
      mocks: {
        $route
      }
    })
    expect(wrapper.vm.$route.path).toBe($route.path)
  })
})

render()

  • Arguments:

    • {Component} component
    • {Object} options
      • {Object} context
        • {Array<Component|Object>|Component} children
      • {Object} slots
        • {Array<Component|Object>|Component|String} default
        • {Array<Component|Object>|Component|String} named
      • {Object} mocks
      • {Object|Array<string>} stubs
      • {Vue} localVue
  • Returns: {Promise<CheerioWrapper>}

  • Options:

See options

  • Usage:

Renders an object to a string and returns a cheerio wrapper.

Cheerio is a jQuery-like library to traverse the DOM in Node.js. It has a similar API to the Vue Test Utils Wrapper.

render uses vue-server-renderer under the hood, to render a component to static HTML.

render is included in the @vue/server-test-utils package.

Without options:

import { render } from '@vue/server-test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', async () => {
    const wrapper = await render(Foo)
    expect(wrapper.text()).toContain('<div></div>')
  })
})

With Vue options:

import { render } from '@vue/server-test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', async () => {
    const wrapper = await render(Foo, {
      propsData: {
        color: 'red'
      }
    })
    expect(wrapper.text()).toContain('red')
  })
})

Default and named slots:

import { render } from '@vue/server-test-utils'
import Foo from './Foo.vue'
import Bar from './Bar.vue'
import FooBar from './FooBar.vue'

describe('Foo', () => {
  it('renders a div', async () => {
    const wrapper = await render(Foo, {
      slots: {
        default: [Bar, FooBar],
        fooBar: FooBar, // Will match <slot name="FooBar" />,
        foo: '<div />'
      }
    })
    expect(wrapper.text()).toContain('<div></div>')
  })
})

Stubbing global properties:

import { render } from '@vue/server-test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', async () => {
    const $route = { path: 'http://www.example-path.com' }
    const wrapper = await render(Foo, {
      mocks: {
        $route
      }
    })
    expect(wrapper.text()).toContain($route.path)
  })
})

renderToString()

  • Arguments:

    • {Component} component
    • {Object} options
      • {Object} context
        • {Array<Component|Object>|Component} children
      • {Object} slots
        • {Array<Component|Object>|Component|String} default
        • {Array<Component|Object>|Component|String} named
      • {Object} mocks
      • {Object|Array<string>} stubs
      • {Vue} localVue
  • Returns: {Promise<string>}

  • Options:

See options

  • Usage:

Renders a component to HTML.

renderToString uses vue-server-renderer under the hood, to render a component to HTML.

renderToString is included in the @vue/server-test-utils package.

Without options:

import { renderToString } from '@vue/server-test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', async () => {
    const str = await renderToString(Foo)
    expect(str).toContain('<div></div>')
  })
})

With Vue options:

import { renderToString } from '@vue/server-test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', async () => {
    const str = await renderToString(Foo, {
      propsData: {
        color: 'red'
      }
    })
    expect(str).toContain('red')
  })
})

Default and named slots:

import { renderToString } from '@vue/server-test-utils'
import Foo from './Foo.vue'
import Bar from './Bar.vue'
import FooBar from './FooBar.vue'

describe('Foo', () => {
  it('renders a div', async () => {
    const str = await renderToString(Foo, {
      slots: {
        default: [Bar, FooBar],
        fooBar: FooBar, // Will match <slot name="FooBar" />,
        foo: '<div />'
      }
    })
    expect(str).toContain('<div></div>')
  })
})

Stubbing global properties:

import { renderToString } from '@vue/server-test-utils'
import Foo from './Foo.vue'

describe('Foo', () => {
  it('renders a div', async () => {
    const $route = { path: 'http://www.example-path.com' }
    const str = await renderToString(Foo, {
      mocks: {
        $route
      }
    })
    expect(str).toContain($route.path)
  })
})

Selectors

A lot of methods take a selector as an argument. A selector can either be a CSS selector, a Vue component, or a find option object.

CSS Selectors

Mount handles any valid CSS selector:

  • tag selectors (div, foo, bar)
  • class selectors (.foo, .bar)
  • attribute selectors ([foo], [foo="bar"])
  • id selectors (#foo, #bar)
  • pseudo selectors (div:first-of-type)

You can also use combinators:

  • direct descendant combinator (div > #bar > .foo)
  • general descendant combinator (div #bar .foo)
  • adjacent sibling selector (div + .foo)
  • general sibling selector (div ~ .foo)

Vue Components

Vue components are also valid selectors.

// Foo.vue

export default {
  name: 'FooComponent'
}
import { shallowMount } from '@vue/test-utils'
import Foo from './Foo.vue'

const wrapper = shallowMount(Foo)
expect(wrapper.is(Foo)).toBe(true)

Find Option Object

Name

Using a find option object, Vue Test Utils allows for selecting elements by a name of component on wrapper components.

const buttonWrapper = wrapper.find({ name: 'my-button' })
buttonWrapper.trigger('click')

Ref

Using a find option object, Vue Test Utils allows for selecting elements by $ref on wrapper components.

const buttonWrapper = wrapper.find({ ref: 'myButton' })
buttonWrapper.trigger('click')

createLocalVue()

  • Arguments:

    • {Object} options
      • {Function} errorHandler
  • Returns:

    • {Component}
  • Usage:

createLocalVue returns a Vue class for you to add components, mixins and install plugins without polluting the global Vue class.

The errorHandler option can be used to handle uncaught errors during component render function and watchers.

Use it with options.localVue:

Without options:

import { createLocalVue, shallowMount } from '@vue/test-utils'
import MyPlugin from 'my-plugin'
import Foo from './Foo.vue'

const localVue = createLocalVue()
localVue.use(MyPlugin)
const wrapper = shallowMount(Foo, {
  localVue,
  mocks: { foo: true }
})
expect(wrapper.vm.foo).toBe(true)

const freshWrapper = shallowMount(Foo)
expect(freshWrapper.vm.foo).toBe(false)

With the errorHandler option:

import { createLocalVue, shallowMount } from '@vue/test-utils'
import Foo from './Foo.vue'

const errorHandler = (err, vm, info) => {
  expect(err).toBeInstanceOf(Error)
}

const localVue = createLocalVue({
  errorHandler
})

// Foo throws an error inside a lifecycle hook
const wrapper = shallowMount(Foo, {
  localVue
})

createWrapper(node [, options])

  • Arguments:

    • {vm|HTMLElement} node
    • {Object} options
      • {Boolean} attachedToDocument
  • Returns:

    • {Wrapper}
  • Usage:

createWrapper creates a Wrapper for a mounted Vue instance, or an HTML element.

import { createWrapper } from '@vue/test-utils'
import Foo from './Foo.vue'

const Constructor = Vue.extend(Foo)
const vm = new Constructor().$mount()
const wrapper = createWrapper(vm)
expect(wrapper.vm.foo).toBe(true)

Config

Vue Test Utils includes a config object to defined options used by Vue Test Utils.

Vue Test Utils Config Options

showDeprecationWarnings

  • type: Boolean
  • default: true

Control whether or not to show deprecation warnings. When set to true, all deprecation warnings are visible in the console.

Example:

import { config } from '@vue/test-utils'

config.showDeprecationWarnings = false

deprecationWarningHandler

  • type: Function

Allows fine-grained control on deprecation warnings. When showDeprecationWarnings is set to true, all deprecation warnings will be passed to this handler with method name as first argument and original message as second.

TIP

This could be useful to log deprecation messages to separate location or to help in gradual upgrade of codebase to latest version of test utils by ignoring certain deprecated functions warnings

Example:

import { config } from '@vue/test-utils'

config.showDeprecationWarnings = true
config.deprecationWarningHandler = (method, message) => {
  if (method === 'emittedByOrder') return

  console.error(msg)
}

stubs

  • type: { [name: string]: Component | boolean | string }
  • default: {}

The stub stored in config.stubs is used by default. Stubs to use in components. These are overwritten by stubs passed in the mounting options.

When passing stubs as an array in the mounting options, config.stubs are converted to an array, and will stub components with a basic component that returns <${component name}-stub>.

Example:

import { config } from '@vue/test-utils'

config.stubs['my-component'] = '<div />'

mocks

  • type: Object
  • default: {}

Like stubs, the values passed to config.mocks are used by default. Any values passed to the mounting options mocks object will take priority over the ones declared in config.mocks.

Example:

import { config } from '@vue/test-utils'

config.mocks['$store'] = {
  state: {
    id: 1
  }
}

methods

  • type: { [name: string]: Function }
  • default: {}

You can configure default methods using the config object. This can be useful for plugins that inject methods to components, like VeeValidate. You can override methods set in config by passing methods in the mounting options.

Example:

import { config } from '@vue/test-utils'

config.methods['getData'] = () => {}

provide

  • type: Object
  • default: {}

Like stubs or mocks, the values passed to config.provide are used by default. Any values passed to the mounting options provide object will take priority over the ones declared in config.provide. Please take note that it is not supported to pass a function as config.provide.

Example:

import { config } from '@vue/test-utils'

config.provide['$logger'] = {
  log: (...args) => {
    console.log(...args)
  }
}

enableAutoDestroy(hook)

  • Arguments:

    • {Function} hook
  • Usage:

enableAutoDestroy will destroy all created Wrapper instances using the passed hook function (for example afterEach). After calling the method, you can revert to the default behavior by calling the resetAutoDestroyState method.

import { enableAutoDestroy, mount } from '@vue/test-utils'
import Foo from './Foo.vue'

// calls wrapper.destroy() after each test
enableAutoDestroy(afterEach)

describe('Foo', () => {
  it('renders a div', () => {
    const wrapper = mount(Foo)
    expect(wrapper.contains('div')).toBe(true)
    // no need to call wrapper.destroy() here
  })
})

resetAutoDestroyState

  • Usage:

After calling enableAutoDestroy you might need to disable auto-destroy behavior (for example when some of your test suites rely on wrapper being persistent across separate tests)

To achieve this you might call resetAutoDestroyState to disable previously registered hook

import {
  enableAutoDestroy,
  resetAutoDestroyState,
  mount
} from '@vue/test-utils'
import Foo from './Foo.vue'

// calls wrapper.destroy() after each test
enableAutoDestroy(afterEach)
// resets auto-destroy after suite completes
afterAll(resetAutoDestroyState)

describe('Foo', () => {
  it('renders a div', () => {
    const wrapper = mount(Foo)
    expect(wrapper.contains('div')).toBe(true)
    // no need to call wrapper.destroy() here
  })
})