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 or setProps()
  • 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 uses vue-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

Made with Slides.com