Unit Testing in Vue β the Essentials
WHAT's A "UNIT?" π§
Intuitively, one can view a unit as the smallest testable part of an application. In procedural programming, a unit could be an entire module, but it is more commonly an individual function or procedure. In object-oriented programming, a unit is often an entire interface, such as a class, but could be an individual method.
When testing in Vue, generally a unit is a component.
βWikipedia
INTRODUCING Vue-test-utils π£
- Official testing utility library for Vue
- Currently in BETA
- Have official examples for Jest, Mocha, tape, and AVA
- github.com/vuejs/vue-test-utilsΒ
LIVE DEMO: COUNTER π’
https://github.com/phanan/counter-meetup
SHALLOW() & MOUNT() π
- create a wrapper contains the mounted & rendered component
- with
shallow()
, child components are stubbed
WRAPPER & WRAPPERARRAY π¬
- wraps around a component, a vnode, or wrappers themselves
- provides methods to test the wrapped object(s): contains(), exists(), html(), is() etc.
import { shallow } from '@vue/test-utils'
import Counter from '@/components/Counter'
describe('Counter.vue', () => {
it('renders', () => {
const wrapper = shallow(Counter)
expect(wrapper.contains('.result')).toBe(true)
})
})
component β black box π¦
Assert a component's public interface, not its implementation details
wrapper.vm.inc()
// this won't work anyway
expect(wrapper.find('.result').text()).toBe('1')
wrapper.find('button').trigger('click')
expect(wrapper.find('.result').text()).toBe('1')
MOCKING π΅
- Set props manually with
propsData
orsetProps()
- Set data manually with mount/shallow options or
setData()
- Sinon/Jest mock functions for external API/dependency mocking
SNAPSHOT TESTING πΈ
- Compare rendered HTML with previously generated snapshot
- Natively supported (Jest/AVA) or available as plugins (Mocha/tape)
- Call
renderToString(Foo)
, which usesvue-server-renderer
- Remember to commit your snapshots!
VUE-TEST-HELPERS π
- Provides useful shortcuts and functions on top of vue-test-utils
- github.com/phanan/vue-test-helpers
import Counter from '@/components/Counter'
describe('Counter.vue', () => {
it('renders', () => {
expect(shallow(Counter).contains('.result', 'button')).toBe(true)
}
it('counts', () => {
expect(shallow(Counter).click('button').find('.result').text()).toBe('1')
}
}
that's it for now! π
github.com/phanan
twitter.com/notphanan
phanan.net
Unit Testing in Vue β The Essentials
By Phan An
Unit Testing in Vue β The Essentials
- 1,509