Testing
How do you unit test a service that depends on a repository?
const repo = { findOneBy: jest.fn() };
const module = await Test.createTestingModule({
providers: [ProductsService, { provide: getRepositoryToken(Product), useValue: repo }],
}).compile();
const service = module.get(ProductsService);
repo.findOneBy.mockResolvedValue(null);
await expect(service.findOne(99)).rejects.toThrow(NotFoundException);getRepositoryToken(Entity) is the token behind @InjectRepository(Entity). For Prisma, provide { provide: PrismaService, useValue: mock }.
What is the difference between unit tests and e2e tests in NestJS?
Unit tests build a small TestingModule with one class and mocked dependencies; they are fast and do not run guards, pipes or filters. E2E tests import AppModule, call createNestApplication() and init(), and send real HTTP requests with Supertest, so routing, validation, auth and filters are all exercised. Remember to apply the same global setup as main.ts (pipes, prefix) in the e2e app.
How do you bypass authentication or replace an external service in e2e tests?
Use the testing module's overrides before compile(): .overrideGuard(JwtAuthGuard).useValue({ canActivate: (ctx) => { ctx.switchToHttp().getRequest().user = testUser; return true; } }) and .overrideProvider(PaymentGateway).useValue(fakeGateway). Better for auth flows: log in through the real endpoint in beforeAll against a seeded test database and use the real token.