Sitemap
Jest command in console.

Organizing Tests in Jest

3 min readMay 6, 2017

--

If you haven’t already tried out Jest, you should. Even if you’re not using React. It’s dead simple and loaded with some cool features like snapshot testing.

Jest does a great job of keeping reports organized. But I’ve noticed, it’s still easy to get disorganized with tests. Why is this? Jest will let you do pretty much anything and still get clean reports. Which is awesome, but that also leaves the door open for negligence. Just because you can get away without paying attention to organization while testing, doesn’t mean you should.

A master craftsman building a chest of drawers, will finish the back of the piece with equal care as the front. Regardless of the fact that the back will be facing a wall most of it’s life. Tests are the back of the cabinet. Any developer with a regard for quality will write tests with equal care and consideration as core functionality. This includes organization.

I’ve seen two popular ways suggested for organizing tests in Jest:

  1. Putting all of your test code into a neatly organized /tests directory.
  2. Putting your test code next to the files they are testing.

Both of these suggestions are valid, but to have the elegance of a master craftsman, we should consider the level of the test that is being written.

Testing Levels

There are many testing levels, but for simplicity we’re just going to talk about two here.

Unit testing refers to tests that verify the functionality of a specific section of code, usually at the function level. In an object-oriented environment, this is usually at the class”

Integration testing is any type of software testing that seeks to verify the interfaces between components against a software design.”

from Wikipedia: Software Testing

Where to put test files

Unit tests run against specific lines of code. So it makes sense to place them right next to that code.

|- /main
| |- index.js
| |- index.test.js

Integration tests run against many lines of code in many files. There is no single place that would make sense, so it’s best to have them in a /tests directory.

|- /main
| |- index.js
|- /supporting
| |- fetch.js
|- /tests
| |- /int
| | |- api.test.js

How to name test files

Naming every level of test *.test.js doesn’t make much sense. So include the type of test right in the name of the file.

Example:index.unit.test.js and api.int.test.js

Conclusion

An ideal set up would look something like this:

|- /main
| |- index.js
| |- index.unit.test.js
|- /supporting
| |- fetch.js
|- /tests
| |- /int
| | |- api.int.test.js

That way it’s easy to find your tests. And with Jest’s pattern matching feature, it makes it simple to run them separately as well. For unit testing run jest unit and for integration testing run jest int.

As with anything, there is no single way of doing this. So if you have other differing practices please share them!

--

--

Responses (8)