This directory contains unit tests for the Library Management REST API project.
tests/
├── setup.ts # Jest setup file
├── helpers/
│ └── mocks.ts # Shared test helpers (mock Request/Response/session)
├── unit/
│ ├── controllers/ # Controller unit tests
│ ├── middlewares/ # Middleware unit tests
│ ├── routes/ # Route registration tests
│ ├── services/ # Service unit tests
│ └── utils/ # Unit tests for src/utils/ (e.g. errors)
└── README.md # This file
npm test
# or
pnpm testnpm run test:watch
# or
pnpm test:watchnpm test -- --coverage
# or
pnpm test -- --coveragenpm test -- tests/unit/utils/errors.test.tsThe project uses Jest for testing with the following coverage goals:
- Statements: > 80%
- Branches: > 80%
- Functions: > 80%
- Lines: > 80%
Coverage reports are generated in the coverage/ directory.
- Test files should be named
*.test.tsor*.spec.ts - Place test files next to the source files or in the
tests/directory
describe('ComponentName', () => {
beforeEach(() => {
// Setup code
});
describe('methodName', () => {
it('should do something', () => {
// Test implementation
});
});
});Common mocks are in tests/helpers/mocks.ts:
createMockRequest()- Creates a mock Express RequestcreateMockResponse()- Creates a mock Express ResponsecreateMockNext()- Creates a mock NextFunctioncreateMockSession()- Creates a mock session with user data
import { createMockRequest, createMockResponse, createMockNext } from '../helpers/mocks';
describe('MyMiddleware', () => {
it('should handle request correctly', () => {
const req = createMockRequest();
const res = createMockResponse();
const next = createMockNext();
// Test implementation
});
});- ✅ Error classes (
src/utils/errors.ts) - ✅ Auth middleware (
src/middlewares/auth.ts) - ✅ Validation middleware (
src/middlewares/validation.ts) - ✅ Auth controller (
src/controllers/auth.controller.ts)
- Integration tests for routes
- Service layer tests
- Database operation tests
- Isolation: Each test should be independent and not rely on other tests
- Mocking: Mock external dependencies (database, APIs, etc.)
- Clear Names: Use descriptive test names that explain what is being tested
- Arrange-Act-Assert: Structure tests with clear setup, execution, and verification
- Coverage: Aim for high coverage but focus on testing critical paths
If you encounter errors like "Cannot find module '@jest/test-sequencer'", try:
pnpm install
# or
npm install- Ensure
tsconfig.jsonincludes the test files - Check that
jest.config.jshas correctmoduleNameMappersettings
- Ensure mocks are imported before the module being tested
- Check that
jest.mock()is called at the top level of the test file
- Ensure
@types/jestis installed - Check that
tsconfig.jsonincludes"jest"in thetypesarray