The Case For Colocating Tests in React

A feature of Jest allows for the running of all *.test.js files throughout your project, regardless of their location. Due to this, some teams have discovered the benefits of co-locating unit tests with the units they are testing.

When you are building any portion of your application, you should inherently be concerned with how you will test that section. And although you can obtain this focus through a project-wide tests/ directory, colocating unit tests with the units they are testing brings you closer mentally to the fundamental values of TDD.

When you are working on a unit of your application, co-locating all related units under a directory for that component makes for a more seamless development experience. This structure helps you focus on component creation and encourages re-usability — if testing your component separated from the rest of the application becomes difficult or you begin pulling in unrelated dependencies, you may need to consider that your component or the utilities related to your component are too coupled. During a review, your peers will be able to look more closely at the component and its unit tests. If you make changes to a singular component, your changes are only within a single directory, making them extremely easy to pull down and review.

This structure allows the developer to not only separate concerns, but also to group together logically related structures which reduce the mental load during development. It makes the developer more concerned with testing their unit and ensuring that a component is both encapsulated and re-usable.

MyComponent/
- MyComponent.js
- MyComponent.css
- MyComponent.test.js

A project-wide tests/ directory is perfect for integration tests, but not so great for unit tests that are inherently related to the smaller units they are testing. Unit tests stored in a project-wide tests/ directory are typically stored in a structure that is replicated from the project folders — instead of replicating this structure and purposefully moving tests away form the focus of the developer, simply include them in the component’s (or utility’s) parent directory.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.