Learn the concept
Test Organization and Structure
Tests can be organized either alongside source files (Component.test.js) or in a separate __tests__ directory. Use describe blocks to group related tests, clear test names that describe behavior, and follow the Given-When-Then or AAA pattern for clarity.
File Organization:
Co-located tests:
Component.js + Component.test.jsSeparate directory:
src/ and __tests__/Naming Conventions:
*.test.js or *.spec.jsTest Structure:
describe: Group related teststest or it: Individual test cases// Co-located structure
// src/
// components/
// Button/
// Button.jsx
// Button.test.jsx
// Button.module.css
// utils/
// format.js
// format.test.js
// Separate __tests__ structure
// src/
// components/
// Button.jsx
// utils/
// format.js
// __tests__/
// components/
// Button.test.jsx
// utils/
// format.test.js
// Jest config for finding tests
module.exports = {
testMatch: [
'**/__tests__/**/*.[jt]s?(x)',
'**/?(*.)+(spec|test).[jt]s?(x)'
]
};
Adopting a co-located test structure (`Component.test.jsx` next to `Component.jsx`) to make it easy for developers to find, understand, and maintain tests alongside the code they test, enhancing module cohesion.
Using a separate `__tests__` directory that mirrors the source directory structure (`src/controllers/users.js` -> `__tests__/controllers/users.test.js`) to keep test files distinct from production code while maintaining clear mapping.
Employing nested `describe` blocks to logically group tests (e.g., `describe('User Management', () => { describe('createUser', ...), describe('deleteUser', ...) })`), improving test readability and allowing granular execution of specific test suites.
Take a project with disorganized tests and refactor its test file structure and naming conventions to follow best practices (co-located or `__tests__` folder) and use descriptive `describe`/`test` blocks.
Create a mock API with several endpoints. Write tests for each endpoint, organizing them into nested `describe` blocks to clearly separate tests for different functionalities.
As the creator of Jest and a pioneer in large-scale JavaScript development, Meta's internal projects heavily utilize well-structured test files, often co-located with components, to manage their vast and rapidly evolving codebase, ensuring developer productivity and code quality.
Spotify's web applications and microservices, which often involve complex features, benefit from structured test files. Clear organization and descriptive test names are crucial for their distributed teams to understand and contribute to various parts of the system efficiently.