Chapter 7: Testing
Testing is essential for building reliable, maintainable applications. This chapter covers unit, integration, and end-to-end (E2E) testing in NestJS, including mocking strategies, test utilities, CI/CD integration, and best practices. We’ll walk through practical examples and explain how to build a robust test suite.
7.1 Why Test?
Testing provides numerous benefits that make it essential for production applications.Benefits of Testing
Catch bugs early:- Find issues before they reach production
- Reduce debugging time
- Prevent regressions
- Make changes knowing tests will catch breakages
- Improve code quality without fear
- Enable continuous refactoring
- Verify requirements are met
- Validate edge cases
- Confirm expected behavior
- Deploy with confidence
- Automate quality checks
- Reduce manual testing
- Tests serve as living documentation
- Show how code should be used
- Provide examples for other developers
Think of tests as a building’s fire alarm system. You do not install fire alarms because you expect fires every day — you install them so that when something goes wrong, you know immediately, before the whole building burns down. Unit tests are smoke detectors in individual rooms (catch small problems fast). Integration tests are sprinkler systems that test whether multiple rooms work together. E2E tests are full fire drills that simulate real emergencies end-to-end. The teams that skip testing are the ones debugging production incidents at 3 AM.
Testing Pyramid
- Fast, isolated, many
- Test individual components
- Mock all dependencies
- Test component interactions
- Use real dependencies where possible
- Moderate speed
- Test full user flows
- Use real everything
- Slow but comprehensive
Testing Strategy Comparison
Decision Framework — What Should I Test and How?
7.2 Unit Testing
Unit tests verify individual components (services, controllers) in isolation. They should be fast and not depend on external systems.Setting Up Tests
NestJS comes with Jest configured by default. Test files should end with.spec.ts and live next to the file they test (not in a separate __tests__ directory). This co-location makes it obvious which code has tests and which does not.
The key utility is Test.createTestingModule() — it creates a mini NestJS application context for your test, wiring up DI exactly like the real app. This means you can swap real providers for mocks and test components in isolation while still using NestJS’s DI system.
Test.createTestingModule().compile() throws “Nest can’t resolve dependencies,” you are missing a provider or mock in the test module. Check that every dependency in the constructor is either provided directly or mocked.
Basic Service Test
7.3 Mocking Dependencies
Mocking dependencies isolates the unit under test and makes tests fast and predictable.Mocking Services
Mocking with Partial
Mocking Modules
Mocking with jest.fn()
expect(repository.create).toHaveBeenCalledWith(dto), you are testing the wiring, not the behavior. A good unit test verifies the output given specific inputs, and uses mocks only to control the environment.
Another Mistake: Forgetting jest.clearAllMocks() in beforeEach. Without it, mock call counts and return values leak between tests, causing flaky failures that are maddening to debug.
7.4 Testing Controllers
Controllers handle HTTP requests and should be tested with mocked services.Controller Test Example
7.5 Integration Testing
Integration tests verify how components work together (e.g., service + database). They are slower than unit tests but catch more real-world issues.Setting Up Integration Tests
7.6 End-to-End (E2E) Testing
E2E tests simulate real user scenarios by making HTTP requests to your app. They test the entire stack, from HTTP layer to database.Setting Up E2E Tests
E2E Test with Authentication
7.7 Testing Async Operations
Handle async operations properly in tests.Testing Promises
Testing Observables
7.8 Test Utilities
NestJS provides utilities to make testing easier.Override Provider
Override Guard
This is one of the most useful testing patterns in NestJS. When testing a controller, you usually do not want to deal with real authentication — you just want to test the route logic. Overriding the guard with a simplecanActivate: () => true lets every request through.
request.user to be populated (because the guard normally sets it), your override guard must also set it. Otherwise, your handler will get undefined when it accesses req.user, and you will spend 20 minutes wondering why your test fails.
Override Interceptor
7.9 Testing Edge Cases
Edge Case 1: Testing request-scoped providers Request-scoped providers create a new instance per request, butTest.createTestingModule() creates singleton instances by default. To test request-scoped behavior, you need to use module.resolve() instead of module.get() — resolve() creates a new instance each time, mimicking request scope.
request.user
When you override a guard in tests, the guard’s canActivate() method no longer runs — which means it no longer attaches the user to the request. If your controller reads req.user, you need your mock guard to set it:
beforeEach (fast but requires careful ordering for foreign keys); (2) Use database transactions — start a transaction in beforeEach, roll it back in afterEach (no data persists, extremely fast); (3) Use unique test data with random IDs so tests never collide.
Edge Case 4: Testing interceptors that use RxJS operators
Interceptors return Observables, which means testing them requires subscribing or converting to promises. Use firstValueFrom() from rxjs to convert the Observable to a promise in your test:
7.9 CI/CD Integration
Automate tests in your CI pipeline to ensure code is always tested before deployment.GitHub Actions Workflow
Test Scripts
7.10 Best Practices
Following best practices ensures your tests are maintainable and effective.Test Organization
Structure tests by feature:Naming Conventions
Test Isolation
Each test should be independent:Use Descriptive Test Names
Test Edge Cases
Keep Tests Fast
- Use mocks for unit tests
- Use in-memory databases for integration tests
- Run E2E tests separately
- Use test parallelization
Coverage Goals
Aim for:- 80%+ coverage for business logic
- 100% coverage for critical paths
- Focus on quality over quantity
Clean Up Resources
Best Practices Checklist
- Write tests for all business logic
- Use mocks for unit tests, real dependencies for integration/E2E
- Keep tests fast and isolated
- Use coverage reports to identify gaps
- Run tests on every commit and pull request
- Name tests clearly and organize by feature
- Clean up resources after each test
- Test edge cases and error scenarios
- Keep test code maintainable
- Use descriptive test names
7.11 Summary
You’ve learned how to test NestJS applications at every level: Key Concepts:- Unit Tests: Test individual components in isolation
- Integration Tests: Test component interactions
- E2E Tests: Test full user flows
- Mocking: Isolate components for testing
- CI/CD: Automate testing in pipelines
- Write tests for all business logic
- Use mocks for unit tests
- Keep tests fast and isolated
- Test edge cases
- Maintain high coverage
- Clean up resources