Structuring Clean Tests
Explore effective methods for structuring unit tests in Jest to enforce clean and maintainable code. Understand how organizing tests into files that correspond to source code enhances navigation and coverage. Learn how to use Jest's describe and test functions properly to create clear, organized test suites that test specific units of code without nesting beyond the allowed structure.
We'll cover the following...
Prioritizing unit testing in our code base enforces clean code. However, imperative to the ability to enforce is a clean and organized testing structure.
Testing files
Our preferred method of breaking out tests into separate files is to simply match the code file structure - ie, one test file to one code file. user.js has a corresponding user.test.js, api.js has api.test.js, etc. Using this structure is helpful for several reasons.
First, it is useful in the maintainability of our tests. Having a one-to-one structure allows us to easily assess what our tests cover, add coverage as our codebase is extended, and navigate our test suites when something is breaking.
In addition, the one-to-one setup helps to enforce only testing one thing at a time. If we find ourselves building classes that live in other files, or needing to import code from lots of other files, we probably aren’t keeping the code ...