Lesson 23 / 34
Testing
Unit test providers and controllers with Jest and Test.createTestingModule, and test HTTP endpoints with supertest.
Unit test with mocked dependencies
Use Test.createTestingModule() to mock and test in isolation.
import { Test, TestingModule } from '@nestjs/testing';
import { UsersService } from './users.service';
describe('UsersService', () => {
let service: UsersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: UsersService,
useValue: { findAll: jest.fn().mockReturnValue([]) }
}
]
}).compile();
service = module.get<UsersService>(UsersService);
});
it('should return an array of users', () => {
expect(service.findAll()).toEqual([]);
});
});E2E test
Test the full request/response cycle with supertest.
import { Test, TestingModule } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';
describe('Users (e2e)', () => {
let app;
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule]
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('GET /users', () => {
return request(app.getHttpServer())
.get('/users')
.expect(200);
});
});Quick check
Quick check: In `Test.createTestingModule`, how do you replace a real service with a fake?
- `.overrideProvider(Service).useValue(fake)`
- Delete the service file
- Set `NODE_ENV=fake`
Answer
`.overrideProvider(Service).useValue(fake)` — `overrideProvider` swaps the dependency inside the test module only.