React: Utilizing factories to test components

Kier Borromeo
2 min readMar 15, 2016

--

Using a simple programming concept to help you test React components.

The Problem

It’s annoying when your cli / your browser console is filled with utter crap due to proptype issues. This usually arises when your component has bazillion proptypes.

This is how your console (browser console/cli) may look like in testing components that have multiple reponsibilities (at least mine when I run karma (a test runner)). It’s annoying because it doesn’t give you a clear context where things went wrong.

What we want is a clear-white console, just like this:

The Solution

This can easily be solved with factories which is a simple concept in programming. So, what are factories? According to Wikipedia:

In object-oriented programming (OOP), a factory is an object for creating other objects — formally a factory is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be “new”.

Example

Let’s try to test dumb component which has this specification (in bullets):

In the following examples, I will be using mocha (a testing framework) + chai.js (an assertion library).

  • It should show the loading class for the update button while we’re updating the todo.
  • It should otherwise when it’s false.
  • It should show the loading class for the delete button while we’re deleting the todo.
  • It should otherwise when it’s false.
  • It should call callback `onUpdate` when form is submitted.
  • It should prevent refreshing of form when it’s submitted.
  • It should call callback `onDelete` when the delete button is pressed
  • It should prevent refreshing of form when it’s submitted.

Here’s what our Component’s propTypes could look like:

Here’s an example of how our test file would look like:

Oops, now we’re started to have the problem we discussed earlier.

Enter, factory functions! Here’s the same test file but uses a factory function to instantiate the component.

The factory function basically provides the defaults for the component we’re testing. And then merges the override (which we’ll provide on each test case) with the defaults props using deepmerge (a library to recursively merge objects).

When To Introduce Factory Functions?

As we discussed earlier, it’s for the best when a component has multiple proptypes to handle.

There are many things you can do achieve with factories. For example, you can use this to stub context which is helpful for components that use React Router’s Link, and so on.

--

--