JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstesting
Prev
testing
junior
structure

How should you structure and organize test files?

test-structure
organization
naming
describe
best-practices
Quick Answer

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.

Detailed Explanation

File Organization:

  1. Co-located tests:

    • Component.js + Component.test.js
    • Easy to find related tests
    • Preferred for component testing
  2. Separate directory:

    • src/ and __tests__/
    • Mirrors source structure
    • Cleaner source folders

Naming Conventions:

  • *.test.js or *.spec.js
  • Descriptive test names
  • Use 'should' or 'when...then' patterns

Test Structure:

  • describe: Group related tests
  • test or it: Individual test cases
  • Nest describe blocks for sub-features

Code Examples

Test file organization
// 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)'
  ]
};

Resources

Jest - Getting Started

docs

Related Questions

What is unit testing and why is it important?

junior
basics

What are the most commonly used Jest matchers?

junior
jest
Previous
How do you test asynchronous code in Jest?