Common mistakes in testing UI components and how to fix them in 5 minutes (Vue.js)

Introduction

Have you ever had to write a new component in Vue and, once the code was done, you tell yourself:

Image for post
Image for post
Photo by Christian Erfurt on Unsplash

UI components testing principles

Here’s a list of important principles I abide by when writing unit tests for UI components, be it React, Vue or any other library. There might be more but these never let me down:

  • Behaviour-driven testing (BDT): Organise the test suite in a way it clearly illustrates what the component does and not how it is done (more details in the section below).
  • Treat Vue components as a black box: a series of inputs (props, user actions, data stores) that produce a well-determined series of outputs (events, renderer output, function calls). These constitute the component’s public interface or the component contract and represent the core focus of our unit tests:
Image for post
Image for post
Vue Component I/O

A “real world” example

Let’s take a real-world example of a simple registration form component.

Image for post
Image for post
RegistrationForm component, you can find the full code here

DOs and DONTs

Let’s now try to write the unit tests for this component together. As promised, I want to keep it simple and informative so here’s another list (yes I like lists as you might have noticed), this time DOs and DONTs to have in mind when deciding what to test and what NOT to test.

1. Test the component contract and not the implementation details

🚫 DON’T assert over implementation details

Behaviour-driven testing (BDT)

🚫 DON’T create a cluttered test suite with a flat structure

  • use nested describe statements for better grouping (not to be overused)

Test a single concept in each test function

🚫 DON’T create tests with many assertions (ideally just one assertion per test)

  • put common setup code in beforeEach statements
  • reduce the number of assertions in each test, ideally to one

Use descriptive sentences when writing test specs

🚫 DON’T use names of internal properties

  • use should or a verb (creates, shows, displays, calls) for an it (test) clause to reflect the expected outcome

Conclusions

By going through all these tips and tricks, I hope it became a bit more clear to you on how to test UI components, what to focus on and how to structure the test files. And if not, please let me know in the comments section how I could make it more clear.

Building nice UI ;)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store