पाठ 23 / 33

Testing

Jest से unit tests, integration tests, और test utilities।

Mocked dependencies के साथ unit test

Isolation में mock और test करने के लिए Test.createTestingModule() का उपयोग करें।

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

supertest से full request/response cycle को test करें।

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);
  });
});