Testing

Backend Testing Guide

Testing Stack

  • Jest as the testing framework
  • Supertest for HTTP testing
  • Test containers for integration tests
  • Mock Service Worker for API mocking

Test Types

Unit Tests

describe('AuthService', () => {
  let service: AuthService;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      providers: [AuthService],
    }).compile();

    service = module.get<AuthService>(AuthService);
  });

  it('should validate JWT token', () => {
    const token = 'valid.jwt.token';
    expect(service.validateToken(token)).toBeTruthy();
  });
});

Integration Tests

describe('ProjectController (e2e)', () => {
  let app: INestApplication;

  beforeEach(async () => {
    const moduleFixture = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
  });

  it('/projects (GET)', () => {
    return request(app.getHttpServer())
      .get('/projects')
      .expect(200)
      .expect([]);
  });
});

Test Organization

src/
├── __tests__/           # Test utilities
├── auth/
│   └── __tests__/      # Auth module tests
├── project/
│   └── __tests__/      # Project module tests
└── vm/
    └── __tests__/      # VM module tests

Best Practices

Test Structure

  1. Arrange - Set up test data
  2. Act - Execute the code under test
  3. Assert - Verify the results

Mocking

  • Use Jest mock functions
  • Mock external services
  • Create test doubles

Test Coverage

  • Aim for 80% coverage
  • Focus on business logic
  • Test edge cases

Running Tests

Unit Tests

# Run unit tests
npm run test

# Run with coverage
npm run test:cov

E2E Tests

# Run e2e tests
npm run test:e2e

# Debug e2e tests
npm run test:e2e:debug

CI/CD Integration

GitHub Actions

test:
  runs-on: ubuntu-latest
  steps:
    - uses: actions/checkout@v2
    - run: npm install
    - run: npm test
    - run: npm run test:e2e

Test Environment

Environment Variables

# test/.env.test
DATABASE_URL=postgresql://test:test@localhost:5432/test
REDIS_URL=redis://localhost:6379/1

Docker Compose

# docker-compose.test.yml
services:
  postgres:
    image: postgres:13
    environment:
      POSTGRES_USER: test
      POSTGRES_PASSWORD: test
      POSTGRES_DB: test

Debugging Tests

VS Code Configuration

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug Tests",
      "program": "${workspaceFolder}/node_modules/.bin/jest",
      "args": ["--runInBand"],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen"
    }
  ]
}

Performance Testing

Load Testing

  • Use Artillery for load testing
  • Monitor response times
  • Test concurrent connections

Memory Leaks

  • Use Node.js –inspect
  • Monitor heap usage
  • Check for memory leaks