# Testing — NestJS: Scalable Node.js APIs बनाना

Source: https://www.skillbyai.com/hi/nestjs/nestjs-testing

> Jest और Test.createTestingModule से providers व controllers का unit test करें, और supertest से HTTP endpoints test करें।

## Mocked dependencies के साथ unit test

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

```typescript
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 करें।

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

त्वरित जाँच

**Quiz:** `Test.createTestingModule` में असली service को fake से कैसे बदलते हैं?

- [x] `.overrideProvider(Service).useValue(fake)`
- [ ] service file delete करके
- [ ] `NODE_ENV=fake` set करके

*Answer:* `.overrideProvider(Service).useValue(fake)`. `overrideProvider` dependency को सिर्फ़ test module के भीतर बदलता है।
