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')
# Vitest
# Mocking useRouter
import { vi } from 'vitest'; const routerPush = vi.fn(); vi.mock('vue-router/composables', () => ({ 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