Vue testing
Table of Contents
:ID: B51EC77B-17C2-4D8C-9F77-8CD069B171C2
Some VueJS unit testing things for a quick reference.
Most of testing is interacting with a wrapper
, so much of what is needed can be
found here https://v1.test-utils.vuejs.org/
# Debugging
# Inspect properties on component
inspect the _setupState
to view refs, computed properties, etc.
wrapper.vm._setupState.someComputedProperty.value
# Emits
# Emitted
returns an array of the emitted event data
wrapper.emitted()['my-event']
# Trigger an emit on a child
const child = wrapper.findComponent(ChildComponent) child.vm.$emit('my-event')
# synced props
Emit the update event to the parent.
child.vm.$emit('update:foo, 'bar');
See also https://v2.vuejs.org/v2/guide/components-custom-events#sync-Modifier
# Flushing promises
Does the code do async stuff that needs to complete before your expectations can be run?
Await on a function that returns a Promise whose resolve is a callback to
setTimeout
.
That’s it. You don’t need a library.
See also https://github.com/kentor/flush-promises/blob/master/index.js
import { flushPromises } from 'path/to/module'; beforeEach(async () => { wrapper.find('form').trigger('submit.prevent'); // thing that makes async HTTP request await flushPromises(); }); it('displays something after the async HTTP request', () => { expect(wrapper.find('.foo').text()).to.contain('bar'); });
# Pinia
# Provision data in a store
import { useMyStore } from '@/stores'; const myStore = useMyStore(); beforeAll() { myStore.stuff = 'stuff' };
# Triggering events
# Keys
await wrapper.trigger('keyup.enter')
# Mocking the vue router
See also Vitest below! https://test-utils.vuejs.org/guide/advanced/vue-router.html#Using-a-Real-Router
import { mount } from '@vue/test-utils' import { createRouter, createWebHistory } from 'vue-router' import { routes } from "@/router" const router = createRouter({ history: createWebHistory(), routes }) const wrapper = mount(MyComponent, { global: { plugins: [router] } })
# Vitest
# Mocking useRouter
import { vi } from 'vitest'; const routerPush = vi.fn(); // spy vi.mock('vue-router', () => ({ useRouter: () => ({ push: routerPush }) })); it(() => expect(routerPush).toHaveBeenCalledWith({});
# Stubbing imported functions
See also https://vitest.dev/api/mock.html
import { vi } from 'vitest'; import { myFunction } from '@/my/component'; vi.mock('@/my/component'); beforeEach(() => { myFunction.mockResolvedValue({}); }); it(() => { expect(myFunction).toHaveBeenCalledWith("foo") })
Use mockReturnValue
for synchronous returns
Warning: Typescript will not like this approach Use this instead:
import { vi } from 'vitest'; const { someFunction } = vi.hoisted(() => { return { someFunction: vi.fn() } }); vi.mock('@/api/myModule, () => { return { default: { someFunction }, someFunction } });