Vue Testing: Mock and Stub
Overview of the terminology
The capability to test your code is a must have for software engineer. In this article I’ll give a brief explanation to get yourself in testing environment for vue.
First thing first, let’s take up some terminology you should know beforehand. The terminology you should know are mock/mock object and stub. I’ll take the definition from an article from circleci.
Mocking means creating a fake version of an external or internal service that can stand in for the real one, helping your tests run more quickly and more reliably. When your implementation interacts with an object’s properties, rather than its function or behavior, a mock can be used.
Stubbing, like mocking, means creating a stand-in, but a stub only mocks the behavior, but not the entire object. This is used when your implementation only interacts with a certain behavior of the object.
Implementation
After knowing how mock and stub works now you should know how to implement this in your vue project. Vue has a built-in library for testing it’s called Vue test utils.
First, to isolate your testing to certain component you can stub the component by using shallowMount
import { shallowMount } from '@vue/test-utils'
import MyComponent from src/components/MyComponent.vueconst wrapper = shallowMount(MyComponent)
Vue test utils also provide several ways to mock certain service of your component.
- Mocking Props
using the wrapper above you can set your props with
wrapper.setProps({})// if the component hasn't been mounted you can use propsData
shallowMount(Component, {
propsData: {
myprop: 'your_props'
}
})
- Mocking Transition
To mock transition on vue you can use Vue.nextTick()
Here is the example that I use in my project
nextTick is ude to test when data changed. Use it immediately after you’ve changed some data to wait for the DOM update.
There are a lot of methods and workaround to mock or stub your code. I Hope this article could be a starting point to do your test on your own