Skip to content

JavaScript

JavaScript Unit Testing

Having good unit tests for your components and methods allows you to more easily make changes to the component, knowing that your key inputs and outputs are still in place and behaving as expected. Without these tests, you may inadvertently break things when refactoring or adding new functionality.

Testing frameworks


Jest

Jest is a testing framework developed by Facebook in order to test React components. It is a little light on features, but it is generally considered to be simpler to use than Mocha. It’s a good tool if you don’t have to do complicated mocking or data stubbing.

Mocha

Mocha is a test framework which is initially designed to be for backend testing of Node.js applications. Mocha is meant to be combined with other testing libraries depending on the functionality you need. It’s commonly paired with Chai, which is an assertion library. Another common pairing is Sinon, which helps you with mocking, stubbing and spying functionality.

This is usually my go-to, I have had lots of headaches with Jest in the past and Mocha has proven itself to be very reliable, even when testing complicated things such as Firebase and Vuex state.

Vitest

Vitest is a new kid on the block and one that I am personally very excited to try. It is meant to be partnered with Vite, which is a build tool, similar to webpack. Vite is potentially a lot faster and has much better integrations with Vue.js, so its likely a better long-term tool for Salt to try.

What to test


Inputs

You want to test to ensure that a component takes in specific inputs:

  • Interactions: Clicking, typing, any “human” interaction
  • Props: The arguments that the components received
  • Data streams: Data incoming from API calls

Outputs

Alongside the given inputs, you want to know that expected output occurs:

  • DOM elements. Observable DOM nodes rendered.
  • Events. Emitted events (using $emit)
  • Side effects. Generally API calls made by the component

Generally speaking, every other part of your component is an implementation detail and you should try avoid testing it. The idea here is that refactoring shouldn’t break your test. If you are testing that a particular paragraph with some class is shown before another one, you are building brittle tests. Rather test that the content which the paragraph should contain is available in the component - it doesn’t matter in a unit test context where or how that content is rendered

Live example

Adding a test for AdminProgressBar