How To Setup React Component In Tests

・3 min read
How To Setup React Component In Tests

in a DRY way

In the examples, the testing stack is Jest and Enzyme, but this pattern can be used in any other combination of test runner and renderer. I would like to show you a simple pattern that we are using in Selleo, and how it came to life.

Initial implementation aka inline setup in every test.

The simple testing setup might look like this:

On every test case, the component receives all props needed for it to be tested. This way of setting up the component has a few problems.

  • The more test cases you have the more you have to repeat the component setup
  • Components having more props are making the setup process take multiple lines
  • Having to specify all props every time makes visual noise so it is not easily visible which prop is important for this test

Second iteration aka default props.

Some of the downsides of the previous pattern can be quickly neutralized by extracting default props and replacing only the props specific for a given test.

This will give you 80% of the effect for 20% of the effort. However, let’s not stop there and go for the full solution, as there is still unnecessary code repeating in the test suite.

  • React and Enzyme imports have to be in every test file which increases the boilerplate a little bit
  • Merging of props with defaults has to be done every time

Third iteration aka buildSetup

Once you extract the basic job, which is rendering of the component to reusable place you can focus on other aspects of your tests.

To make buildSetup available in every test file without importing it you have to:

The notable aspects of this solution are:

  • You are importing React and enzyme only in the buildSetup file, so two imports less for all your testing files.
  • Default Props are merged automatically with overriding props passed to the setup function.
  • Different prop merging strategies can be implemented in buildSetup file and it will be used across the whole test suite

Summary

Even though there are different ways of setting up React components in tests, we have field tested this one in Selleo on a few projects already, and it is working well for us. How do you setup components on your projects? Would you use buildSetup yourself or prefer a different way? Leave a comment.

Our services
See what we can create for You
Our Services