On unit testing

with Jest

Jest framework

  • Almost 0 config 🤷🏾‍♀️
  • Snapshot testing 📸
  • Isolated ‼️
  • Fast 🔥
  • Coverage 👀
  • Easy API 🙏🏾

Delightful JavaScript Testing Framework with a focus on simplicity.

Testing pyramid... 😅

Unit

Integration

E2E

Static analysis: Eslint or static

type checking (TS or Flow)

Jest

Cypress

💵

💵

Ultimate guide 🔥

💵

💵

Ultimate guide 🔥

Unit testing

About Unity

Unit tests should focus on behaviors that are mostly pure:

  • Given the same inputs, always return the same output

  • Have no side-effects

Isolate side effects from business rules and domain logic.

 - Eric Elliot

All tests must be isolated from other tests. Tests should have no shared mutable state.

About Unity

Factory functions

Example

Search Box

Input

Clear Button

Search Button

Store

Input component

  • reflects local state?
  • fires events?

 

Clear button component

  • makes expected calls?

 

Search button component

  • makes expected calls?

Unit testing this UI?

+ Some smoke tests 💨 ?

Business Logic and global state in Vue apps?

Utils

Factory

Main principles

Use factory functions to provide (shared) setups.

 

Try to focus on the most important parts (no mandatory level code coverage)

 

Try to use "equal" comparisons instead of weird assertions (better readability).

Main principles

Isolation: pure (no side effects) and controlled context

  • Too much isolation: mocking++ is also bad.
  • Too much isolation reduces the bug catchs.

 

Confidence:

  • Our test suite must enable confidence.
  • Our architecture must be testable.
  • Our logic models might be rethinked (private class fields)

Unit VS Integration

Unit VS Integration

Unit VS Integration

it('has the expected html structure', () => {
  expect(wrapper.element).toMatchSnapshot()
})

Snapshot testing

  it('emits correct structure to new fields', () => {
    // arrange
    wrapper.setProps({
      fields: [
        {
          type: 'text',
          labelledAs: 'My author',
        },
      ],
    })
    // act
    const position = 0
    wrapper.vm.updateModel('value', 'key', position)
    // assert
    expect(wrapper.emitted('update')[position]).toEqual([[{ key: 'value' }]])
    expect(wrapper.vm.currentModelValues).toEqual([{ key: 'value' }])
  })

Testing methods, local state and emissions

What to test on unit tests, then?

  • Local state modifications (most of the times you don't need to test the defaults)
  • Methods inputs and outputs
  • Events with spected structure
  • Calls contracts: API, store...

Jest + Vue

demo

on testing with jest (Part I)

By Paul Melero

on testing with jest (Part I)

First round of slides on testing wit jest. What kind of things should we test on the unit tests?

  • 87
Loading comments...

More from Paul Melero