### Install vue-jest preprocessor Source: https://v1.test-utils.vuejs.org/guides/using-with-typescript Installs vue-jest to teach Jest how to process .vue files. ```bash npm install --save-dev vue-jest ``` -------------------------------- ### createLocalVue without options Source: https://v1.test-utils.vuejs.org/api/createLocalVue.html Creates a local Vue class to install a plugin and mount a component without polluting the global Vue class. Use the returned localVue with the localVue option of shallowMount. The example installs MyPlugin on the local Vue, asserts the wrapper's foo data is true, then shows a fresh wrapper without the plugin has foo as false. ```javascript 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) ``` -------------------------------- ### findAll usage example Source: https://v1.test-utils.vuejs.org/api/wrapper/findall Shows how to use findAll with a CSS selector to get a WrapperArray and access an element with .at(0). Also demonstrates the deprecated usage of findAll with a component, which should be replaced with findAllComponents. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' import Bar from './Bar.vue' const wrapper = mount(Foo) const div = wrapper.findAll('div').at(0) expect(div.is('div')).toBe(true) const bar = wrapper.findAll(Bar).at(0) // Deprecated usage expect(bar.is(Bar)).toBe(true) ``` -------------------------------- ### Install Vue Test Utils and vue-jest manually Source: https://v1.test-utils.vuejs.org/installation Manual installation of Vue Test Utils and vue-jest to process Single-File Components with Jest. ```bash $ npm install --save-dev @vue/test-utils@legacy vue-jest ``` -------------------------------- ### Install Vue CLI globally Source: https://v1.test-utils.vuejs.org/guides/using-with-typescript Installs the Vue CLI globally via npm, required to create a new project. ```bash $ npm install -g @vue/cli ``` -------------------------------- ### findAllComponents example with component selector Source: https://v1.test-utils.vuejs.org/api/wrapper/findallcomponents Shows how to use findAllComponents with a component selector to find all matching Vue components in a mounted wrapper. The example mounts Foo, finds all Bar components, and asserts the first one exists and that there is exactly one. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' import Bar from './Bar.vue' const wrapper = mount(Foo) const bar = wrapper.findAllComponents(Bar).at(0) expect(bar.exists()).toBeTruthy() const bars = wrapper.findAllComponents(Bar) expect(bars).toHaveLength(1) ``` -------------------------------- ### Install Vue Router on localVue Source: https://v1.test-utils.vuejs.org/guides/using-with-vue-router Creates a localVue and installs Vue Router on it to avoid adding read-only $route and $router properties to the global Vue prototype. Then mounts a component with the router instance. ```javascript import { shallowMount, createLocalVue } from '@vue/test-utils' import VueRouter from 'vue-router' const localVue = createLocalVue() localVue.use(VueRouter) const router = new VueRouter() shallowMount(Component, { localVue, router }) ``` -------------------------------- ### Install Jest and Vue Test Utils Source: https://v1.test-utils.vuejs.org/guides/using-with-typescript Installs Jest and Vue Test Utils as dev dependencies for testing. ```bash $ npm install --save-dev jest @vue/test-utils ``` -------------------------------- ### setProps example Source: https://v1.test-utils.vuejs.org/api/wrapper-array Sets props on all Wrapper instances in the WrapperArray and forces update. Requires each Wrapper to contain a Vue instance. The example uses findAll to get an array of Bar components and sets the 'foo' prop to 'bar'. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' import Bar from './Bar.vue' test('setProps demo', async () => { const wrapper = mount(Foo) const barArray = wrapper.findAll(Bar) await barArray.setProps({ foo: 'bar' }) expect(barArray.at(0).vm.foo).toBe('bar') }) ``` -------------------------------- ### setData example with mount and findAll Source: https://v1.test-utils.vuejs.org/api/wrapper-array/setdata Sets data on each Wrapper in a WrapperArray returned by findAll. Requires every Wrapper to contain a Vue instance. The example uses an async test and awaits the setData call before asserting the updated data. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' import Bar from './Bar.vue' test('setData demo', async () => { const wrapper = mount(Foo) const barArray = wrapper.findAll(Bar) await barArray.setData({ foo: 'bar' }) expect(barArray.at(0).vm.foo).toBe('bar') }) ``` -------------------------------- ### setData example with mount and async test Source: https://v1.test-utils.vuejs.org/api/wrapper/setdata Shows how to use setData to update component data and assert the change. The Wrapper must contain a Vue instance. The example uses an async test and awaits setData. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' test('setData demo', async () => { const wrapper = mount(Foo) await wrapper.setData({ foo: 'bar' }) expect(wrapper.vm.foo).toBe('bar') }) ``` -------------------------------- ### Install ts-jest Source: https://v1.test-utils.vuejs.org/guides/using-with-typescript Installs ts-jest to compile TypeScript files in Jest. ```bash $ npm install --save-dev ts-jest ``` -------------------------------- ### Using at() to get a Wrapper by index Source: https://v1.test-utils.vuejs.org/api/wrapper-array/at Shows how to use `at()` on a WrapperArray to get a specific Wrapper. The example uses `findAll('div')` to get all divs, then `at(1)` for the second div and `at(-1)` for the last div, verifying each with `is('div')`. ```javascript import { shallowMount } from '@vue/test-utils' import Foo from './Foo.vue' const wrapper = shallowMount(Foo) const divArray = wrapper.findAll('div') const secondDiv = divArray.at(1) expect(secondDiv.is('div')).toBe(true) const lastDiv = divArray.at(-1) expect(lastDiv.is('div')).toBe(true) ``` -------------------------------- ### setValue example with text input and select Source: https://v1.test-utils.vuejs.org/api/wrapper/setvalue Demonstrates using setValue on a text input and a select element, including a multi-select. Requires an async test function and awaiting setValue. The example asserts the element values after setting. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' test('setValue demo', async () => { const wrapper = mount(Foo) const textInput = wrapper.find('input[type="text"]') await textInput.setValue('some value') expect(wrapper.find('input[type="text"]').element.value).toBe('some value') const select = wrapper.find('select') await select.setValue('option value') expect(wrapper.find('select').element.value).toBe('option value') // requires ` }) test('setValue demo', async () => { const wrapperArray = wrapper.findAll('.foo') expect(wrapper.vm.t1).toEqual('') expect(wrapper.vm.t2).toEqual('') await wrapperArray.setValue('foo') expect(wrapper.vm.t1).toEqual('foo') expect(wrapper.vm.t2).toEqual('foo') }) ``` -------------------------------- ### Keyboard Example - Test Source: https://v1.test-utils.vuejs.org/guides Tests for the keyboard component: default quantity, arrow key increments/decrements, escape resets, and 'a' sets to 13. ```javascript import QuantityComponent from '@/components/QuantityComponent' import { mount } from '@vue/test-utils' describe('Key event tests', () => { it('Quantity is zero by default', () => { const wrapper = mount(QuantityComponent) expect(wrapper.vm.quantity).toBe(0) }) it('Up arrow key increments quantity by 1', async () => { const wrapper = mount(QuantityComponent) await wrapper.trigger('keydown.up') expect(wrapper.vm.quantity).toBe(1) }) it('Down arrow key decrements quantity by 1', async () => { const wrapper = mount(QuantityComponent) wrapper.vm.quantity = 5 await wrapper.trigger('keydown.down') expect(wrapper.vm.quantity).toBe(4) }) it('Escape sets quantity to 0', async () => { const wrapper = mount(QuantityComponent) wrapper.vm.quantity = 5 await wrapper.trigger('keydown.esc') expect(wrapper.vm.quantity).toBe(0) }) it('Magic character "a" sets quantity to 13', async () => { const wrapper = mount(QuantityComponent) await wrapper.trigger('keydown', { key: 'a' }) expect(wrapper.vm.quantity).toBe(13) }) }) ``` -------------------------------- ### setChecked example with mount and findAll Source: https://v1.test-utils.vuejs.org/api/wrapper-array/setchecked Example of using setChecked on a WrapperArray to set checkboxes and radio buttons. It mounts a component with v-model bindings, finds elements with class 'foo', and verifies the model updates after calling setChecked. ```javascript import { mount } from '@vue/test-utils' test('setChecked demo', async () => { const wrapper = mount({ data() { return { t1: false, t2: '' } }, template: `
` }) const wrapperArray = wrapper.findAll('.foo') expect(wrapper.vm.t1).toEqual(false) expect(wrapper.vm.t2).toEqual('') await wrapperArray.setChecked() expect(wrapper.vm.t1).toEqual(true) expect(wrapper.vm.t2).toEqual('foo') }) ``` -------------------------------- ### Using get to assert element existence Source: https://v1.test-utils.vuejs.org/api/wrapper/get.html Mounts a component and uses `get` to assert an element exists, throwing an error with a specific message if not found. The error message includes the selector and the actual DOM. ```javascript import { mount } from '@vue/test-utils' const wrapper = mount(Foo) // similar to `wrapper.find`. // `get` will throw an error if an element is not found. `find` will do nothing. expect(wrapper.get('.does-exist')) expect(() => wrapper.get('.does-not-exist')) .to.throw() .with.property( 'message', 'Unable to find .does-not-exist within:
the actual DOM here...
' ) ``` -------------------------------- ### isVisible() example Source: https://v1.test-utils.vuejs.org/api/wrapper/isvisible Mounts a component and asserts that the root element is visible and a child element with class `.is-not-visible` is not visible. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' const wrapper = mount(Foo) expect(wrapper.isVisible()).toBe(true) expect(wrapper.find('.is-not-visible').isVisible()).toBe(false) ``` -------------------------------- ### contains example with shallowMount and findAll Source: https://v1.test-utils.vuejs.org/api/wrapper-array/contains Shallow mounts Foo, finds all div elements, and asserts that each div contains a 'p' element and a Bar component. Returns true if all wrappers contain the selector. ```javascript import { shallowMount } from '@vue/test-utils' import Foo from './Foo.vue' import Bar from './Bar.vue' const wrapper = shallowMount(Foo) const divArray = wrapper.findAll('div') expect(divArray.contains('p')).toBe(true) expect(divArray.contains(Bar)).toBe(true) ``` -------------------------------- ### Keyboard example: test Source: https://v1.test-utils.vuejs.org/guides/dom-events Tests for the QuantityComponent: default quantity, arrow key increments/decrements, Escape clears, and 'a' sets to 13. Uses `wrapper.trigger('keydown.up')` etc. ```javascript import QuantityComponent from '@/components/QuantityComponent' import { mount } from '@vue/test-utils' describe('Key event tests', () => { it('Quantity is zero by default', () => { const wrapper = mount(QuantityComponent) expect(wrapper.vm.quantity).toBe(0) }) it('Up arrow key increments quantity by 1', async () => { const wrapper = mount(QuantityComponent) await wrapper.trigger('keydown.up') expect(wrapper.vm.quantity).toBe(1) }) it('Down arrow key decrements quantity by 1', async () => { const wrapper = mount(QuantityComponent) wrapper.vm.quantity = 5 await wrapper.trigger('keydown.down') expect(wrapper.vm.quantity).toBe(4) }) it('Escape sets quantity to 0', async () => { const wrapper = mount(QuantityComponent) wrapper.vm.quantity = 5 await wrapper.trigger('keydown.esc') expect(wrapper.vm.quantity).toBe(0) }) it('Magic character "a" sets quantity to 13', async () => { const wrapper = mount(QuantityComponent) await wrapper.trigger('keydown', { key: 'a' }) expect(wrapper.vm.quantity).toBe(13) }) }) ``` -------------------------------- ### createWrapper usage with mounted Vue instance Source: https://v1.test-utils.vuejs.org/api/createwrapper Creates a Wrapper for a mounted Vue instance. The example imports createWrapper, extends a Vue component, mounts it, and then creates a wrapper to access the instance's properties. ```javascript 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) ``` -------------------------------- ### Mouse Click Example - Component under test Source: https://v1.test-utils.vuejs.org/guides A Vue component with two buttons that call a prop function with 'yes' or 'no'. ```vue ``` -------------------------------- ### render() without options Source: https://v1.test-utils.vuejs.org/api/render Renders a component to static HTML and returns a Cheerio wrapper. The example imports render from @vue/server-test-utils and asserts the rendered HTML contains a div. ```javascript 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('
') }) }) ``` -------------------------------- ### find: Chaining find calls Source: https://v1.test-utils.vuejs.org/api/wrapper Shows that find calls can be chained. The example finds a component by ref and then finds an element with class 'icon' within it. ```javascript const button = wrapper.find({ ref: 'testButton' }) expect(button.find('.icon').exists()).toBe(true) ``` -------------------------------- ### Example component with a method that makes an API call Source: https://v1.test-utils.vuejs.org/upgrading-to-v1 Shows a Vue component with a `created` hook that calls `getData`, which uses `axios.get`. This is the component you might want to stub in tests. ```javascript const Foo = { created() { this.getData() }, methods: { getData() { axios.get('...') } } } ``` -------------------------------- ### setProps example Source: https://v1.test-utils.vuejs.org/api/wrapper-array/setprops Sets props on all Wrappers in a WrapperArray and verifies the prop value on the first Wrapper. Requires every Wrapper to contain a Vue instance. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' import Bar from './Bar.vue' test('setProps demo', async () => { const wrapper = mount(Foo) const barArray = wrapper.findAll(Bar) await barArray.setProps({ foo: 'bar' }) expect(barArray.at(0).vm.foo).toBe('bar') }) ``` -------------------------------- ### Mock Transitions - Component with Transition Source: https://v1.test-utils.vuejs.org/guides/common-tips A component that uses the wrapper to conditionally render a paragraph. This is the component under test for transition mocking examples. ```html ``` -------------------------------- ### Add Jest plugin via Vue CLI Source: https://v1.test-utils.vuejs.org/installation Run this command to add the unit-jest plugin to a Vue CLI project. It installs Jest and creates a jest.config.js file with sensible defaults. ```bash $ vue add unit-jest ``` -------------------------------- ### render() with Vue options Source: https://v1.test-utils.vuejs.org/api/render Renders a component with propsData option. The example passes a color prop and asserts the rendered output contains the value 'red'. ```javascript 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') }) }) ``` -------------------------------- ### get: Find element that should exist, throws if not found Source: https://v1.test-utils.vuejs.org/api/wrapper Works like find but throws an error if nothing matches the selector. Use when the element should exist. The example shows that get throws with a specific message when the element is missing. ```javascript import { mount } from '@vue/test-utils' const wrapper = mount(Foo) // similar to `wrapper.find`. // `get` will throw an error if an element is not found. `find` will do nothing. expect(wrapper.get('.does-exist')) expect(() => wrapper.get('.does-not-exist')) .to.throw() .with.property( 'message', 'Unable to find .does-not-exist within:
the actual DOM here...
' ) ``` -------------------------------- ### isVueInstance() usage example Source: https://v1.test-utils.vuejs.org/api/wrapper-array/isvueinstance Shows how to use the deprecated isVueInstance() method on a WrapperArray. It mounts a Foo component, finds all Bar components, and asserts that each is a Vue instance. The method returns a boolean. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' import Bar from './Bar.vue' const wrapper = mount(Foo) const barArray = wrapper.findAll(Bar) expect(barArray.isVueInstance()).toBe(true) ``` -------------------------------- ### isVisible Example Source: https://v1.test-utils.vuejs.org/api/wrapper-array/isvisible Mounts a component and asserts visibility of all wrappers. Returns false if any ancestor has display:none, visibility:hidden, opacity:0, is inside a collapsed details tag, or has hidden attribute. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' const wrapper = mount(Foo) expect(wrapper.isVisible()).toBe(true) expect(wrapper.findAll('.is-not-visible').isVisible()).toBe(false) expect(wrapper.findAll('.is-visible').isVisible()).toBe(true) ``` -------------------------------- ### render() with mocks for global properties Source: https://v1.test-utils.vuejs.org/api/render Renders a component with mocks option to stub global properties like $route. The example mocks $route and asserts the rendered output contains the mocked path. ```javascript 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) }) }) ``` -------------------------------- ### html: Get Wrapper DOM node HTML string Source: https://v1.test-utils.vuejs.org/api/wrapper Returns the HTML of the Wrapper's DOM node as a string. The example mounts Foo and expects the HTML to be '

Foo

'. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' const wrapper = mount(Foo) expect(wrapper.html()).toBe('

Foo

') ``` -------------------------------- ### render() with default and named slots Source: https://v1.test-utils.vuejs.org/api/render Renders a component with slots option, including default and named slots. The example shows passing components and a string for the default slot, and a component for a named slot. ```javascript 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 , foo: '
' } }) expect(wrapper.text()).toContain('
') }) }) ``` -------------------------------- ### emitted: Get custom events emitted by wrapper Source: https://v1.test-utils.vuejs.org/api/wrapper Returns an object of custom events emitted by the wrapper's vm. The example shows how to assert event existence, count, and payload. The method returns the same object each call, so it updates when new events fire. ```javascript import { mount } from '@vue/test-utils' test('emit demo', async () => { const wrapper = mount(Component) wrapper.vm.$emit('foo') wrapper.vm.$emit('foo', 123) await wrapper.vm.$nextTick() // Wait until $emits have been handled /* wrapper.emitted() returns the following object: { foo: [[], [123]] } */ // assert event has been emitted expect(wrapper.emitted().foo).toBeTruthy() // assert event count expect(wrapper.emitted().foo.length).toBe(2) // assert event payload expect(wrapper.emitted().foo[1]).toEqual([123]) }) ``` ```javascript // assert event has been emitted expect(wrapper.emitted('foo')).toBeTruthy() // assert event count expect(wrapper.emitted('foo').length).toBe(2) // assert event payload expect(wrapper.emitted('foo')[1]).toEqual([123]) ``` ```javascript const emitted = wrapper.emitted() expect(emitted.foo.length).toBe(1) // do something to make `wrapper` emit the "foo" event expect(emitted.foo.length).toBe(2) ``` -------------------------------- ### shallowMount stubbing global properties Source: https://v1.test-utils.vuejs.org/api Usage of shallowMount() with the mocks option to stub global properties. The example mocks $route and asserts that the wrapper's vm has the mocked path. ```javascript 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) }) }) ``` -------------------------------- ### get(selector) Source: https://v1.test-utils.vuejs.org/api/wrapper Works just like find but will throw an error if nothing matching the given selector is found. Use this method when getting an element that should exist. Note: Using get to search for a Component is deprecated; use getComponent instead. ```APIDOC ## get(selector) ### Description Works just like find but will throw an error if nothing matching the given selector is found. You should use `find` when searching for an element that may not exist. You should use this method when getting an element that should exist and it will provide a nice error message if that is not the case. ### Method get ### Arguments - **selector** - The selector to search for ### Returns Throws an error if no matching element is found. ### Deprecation Warning Using `get` to search for a Component is deprecated and will be removed. Use `getComponent` instead. ### Example ``` import { mount } from '@vue/test-utils' const wrapper = mount(Foo) // similar to `wrapper.find`. // `get` will throw an error if an element is not found. `find` will do nothing. expect(wrapper.get('.does-exist')) expect(() => wrapper.get('.does-not-exist')) .to.throw() .with.property( 'message', 'Unable to find .does-not-exist within:
the actual DOM here...
' ) ``` ``` -------------------------------- ### Create Babel config file Source: https://v1.test-utils.vuejs.org/installation Create a babel.config.json or .babelrc.json file with the @babel/preset-env preset. ```json { "presets": ["@babel/preset-env"] } ``` -------------------------------- ### Use default and named slots Source: https://v1.test-utils.vuejs.org/api/mount Shows how to pass default and named slots to mount(). The slots object includes an array for default, a component for fooBar, and a string for foo. Includes a comment that fooBar matches ``. ```javascript 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 ``. foo: '
' } }) expect(wrapper.contains('div')).toBe(true) }) }) ``` -------------------------------- ### provide Source: https://v1.test-utils.vuejs.org/api/options.html Pass properties for components to use in injection. See provide/inject. ```APIDOC ## provide ### Description Pass properties for components to use in injection. See provide/inject. ### Parameters - **provide** (Object) - Required - The properties to provide for injection. ### Example ``` const Component = { inject: ['foo'], template: '
{{this.foo()}}
' } const wrapper = shallowMount(Component, { provide: { foo() { return 'fooValue' } } }) expect(wrapper.text()).toBe('fooValue') ``` ``` -------------------------------- ### Mouse click example: component under test Source: https://v1.test-utils.vuejs.org/guides/dom-events A Vue component with two buttons that call a prop function with 'yes' or 'no'. Used in the mouse click test example. ```html ``` -------------------------------- ### Set default provide values with config.provide Source: https://v1.test-utils.vuejs.org/api/config Values passed to config.provide are used by default. Mounting options provide take priority. Note: passing a function as config.provide is not supported. ```javascript import { config } from '@vue/test-utils' config.provide['$logger'] = { log: (...args) => { console.log(...args) } } ``` -------------------------------- ### Stub global properties with mocks Source: https://v1.test-utils.vuejs.org/api/mount Shows how to stub global properties using the mocks option. Defines a $route object and passes it to mount(), then asserts wrapper.vm.$route.path equals the original path. ```javascript 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) }) }) ``` -------------------------------- ### Using getComponent with mount and selectors Source: https://v1.test-utils.vuejs.org/api/wrapper/getcomponent Mounts a component and uses getComponent to retrieve a child component by instance, name, or ref. getComponent throws an error if no matching component is found, unlike findComponent which does nothing. The example also shows the error message for a non-existent component name. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' import Bar from './Bar.vue' const wrapper = mount(Foo) // similar to `wrapper.findComponent`. // `getComponent` will throw an error if an element is not found. `findComponent` will do nothing. expect(wrapper.getComponent(Bar)) // => gets Bar by component instance expect(wrapper.getComponent({ name: 'bar' })) // => gets Bar by `name` expect(wrapper.getComponent({ ref: 'bar' })) // => gets Bar by `ref` expect(() => wrapper.getComponent({ name: 'does-not-exist' })) .to.throw() .with.property( 'message', "Unable to get a component named 'does-not-exist' within:
the actual DOM here...
" ) ``` -------------------------------- ### Using attachTo with a CSS selector and an HTMLElement Source: https://v1.test-utils.vuejs.org/api/options.html Shows how to mount a component with attachTo using a CSS selector string ('#root') and then an HTMLElement (document.getElementById('root')). The example creates a div with id 'root', appends it to the document body, mounts the component, verifies the element's parent is not null, and calls wrapper.destroy() after each mount. ```javascript const div = document.createElement('div') div.id = 'root' document.body.appendChild(div) const Component = { template: '
ABC
' } let wrapper = mount(Component, { attachTo: '#root' }) expect(wrapper.vm.$el.parentNode).not.toBeNull() wrapper.destroy() wrapper = mount(Component, { attachTo: document.getElementById('root') }) expect(wrapper.vm.$el.parentNode).not.toBeNull() wrapper.destroy() ``` -------------------------------- ### Set default methods with config.methods Source: https://v1.test-utils.vuejs.org/api/config Configure default methods using the config object, useful for plugins that inject methods. Override by passing methods in mounting options. ```javascript import { config } from '@vue/test-utils' config.methods['getData'] = () => {} ``` -------------------------------- ### Create a new Vue project Source: https://v1.test-utils.vuejs.org/guides/using-with-typescript Creates a new Vue project with the Vue CLI. In the prompt, select 'Manually select features' and choose TypeScript. ```bash $ vue create hello-world ``` -------------------------------- ### Using html() to assert rendered HTML Source: https://v1.test-utils.vuejs.org/api/wrapper/html.html Mounts a component and asserts that the wrapper's HTML matches the expected string. The example imports mount from '@vue/test-utils' and a Foo component, then checks that wrapper.html() equals '

Foo

'. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' const wrapper = mount(Foo) expect(wrapper.html()).toBe('

Foo

') ``` -------------------------------- ### Mouse Click Example - Test Source: https://v1.test-utils.vuejs.org/guides Test that clicks the 'yes' button and verifies the spy is called with 'yes'. ```javascript import YesNoComponent from '@/components/YesNoComponent' import { mount } from '@vue/test-utils' import sinon from 'sinon' it('Click on yes button calls our method with argument "yes"', async () => { const spy = sinon.spy() const wrapper = mount(YesNoComponent, { propsData: { callMe: spy } }) await wrapper.find('button.yes').trigger('click') spy.should.have.been.calledWith('yes') }) ``` -------------------------------- ### Mount component with Vue options (propsData) Source: https://v1.test-utils.vuejs.org/api/mount Shows how to pass propsData to mount() and verify the prop value. The wrapper.props().color is expected to be 'red'. ```javascript 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') }) }) ``` -------------------------------- ### Using props() and props('key') with mount Source: https://v1.test-utils.vuejs.org/api/wrapper/props Mounts a component with propsData and checks that props() returns the props object and props('bar') returns the specific prop value. ```javascript import { mount } from '@vue/test-utils' import Foo from './Foo.vue' const wrapper = mount(Foo, { propsData: { bar: 'baz' } }) expect(wrapper.props().bar).toBe('baz') expect(wrapper.props('bar')).toBe('baz') ``` -------------------------------- ### get(selector) Source: https://v1.test-utils.vuejs.org/api/wrapper/get.html Searches for an element matching the given selector and throws an error if nothing is found. Use this when the element should exist. ```APIDOC ## get(selector) ### Description Searches for an element matching the given selector and throws an error if nothing is found. Use this when the element should exist. ### Method `get` ### Parameters - **selector** (string or Component) - Required - The CSS selector or component to search for. Note: Using `get` to search for a Component is deprecated; use `getComponent` instead. ### Behavior - Works like `find` but throws an error if no matching element is found. - Use `find` when searching for an element that may not exist. - Use `get` when getting an element that should exist, providing a nice error message if not. ### Example ```js import { mount } from '@vue/test-utils' const wrapper = mount(Foo) // similar to `wrapper.find`. // `get` will throw an error if an element is not found. `find` will do nothing. expect(wrapper.get('.does-exist')) expect(() => wrapper.get('.does-not-exist')) .to.throw() .with.property( 'message', 'Unable to find .does-not-exist within:
the actual DOM here...
' ) ``` ### Error Handling - Throws an error if no element matches the selector. - Error message includes the selector and the actual DOM content. ``` -------------------------------- ### Mount component without options Source: https://v1.test-utils.vuejs.org/api/mount Basic usage of mount() to render a component and assert it contains a div. Imports mount and the component, then uses expect(wrapper.contains('div')).toBe(true). ```javascript 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) }) }) ``` -------------------------------- ### Stub router-link and router-view Source: https://v1.test-utils.vuejs.org/guides/using-with-vue-router Uses shallowMount with stubs for 'router-link' and 'router-view' to make them available in tests without installing Vue Router. ```javascript import { shallowMount } from '@vue/test-utils' shallowMount(Component, { stubs: ['router-link', 'router-view'] }) ``` -------------------------------- ### Vue component selector example (Foo.vue) Source: https://v1.test-utils.vuejs.org/api Defines a Vue component named 'FooComponent' used as a selector in Vue Test Utils. ```vue // Foo.vue export default { name: 'FooComponent' } ``` -------------------------------- ### Store configuration (store-config.js) Source: https://v1.test-utils.vuejs.org/guides/using-with-vuex.html Defines the store configuration with state, mutations, and getters. This config is used to create a running store instance in tests. ```javascript // store-config.js import mutations from './mutations' import getters from './getters' export default { state: { count: 0 }, mutations, getters } ``` -------------------------------- ### Keyboard Example - Component under test Source: https://v1.test-utils.vuejs.org/guides A Vue component that increments/decrements quantity using arrow keys, clears with Escape, and sets to 13 with 'a'. ```vue ``` -------------------------------- ### Axios mock for API call test Source: https://v1.test-utils.vuejs.org/guides/testing-async-components Mock implementation of axios used in the example. It returns a resolved promise with data 'value'. ```javascript export default { get: () => Promise.resolve({ data: 'value' }) } ``` -------------------------------- ### Add Babel options to package.json Source: https://v1.test-utils.vuejs.org/installation Alternative to a separate Babel config file: add the Babel preset directly to package.json. ```json { "babel": { "presets": ["@babel/preset-env"] } } ```