NestJS course ยท Module 7: Testing

Testing - Trials Before Setting Out on a Campaign

7 min read ยท
In this lesson7

Testers of the legions! Consul Caesar.js knows well that no wise legionary sets out on a campaign without thoroughly checking every element of the fort. Today you will learn the art of testing - the most important skill of every professional legionary-programmer!

In a Roman fort there is no room for errors. If a catapult fails to fire at a crucial moment, if the walls don't withstand a siege, or if the defense system fails during an attack - it means disaster! That's why every element must be tested before we set out on a campaign.

Why Is Testing Critical?

Imagine you are a centurion responsible for the safety of the entire legion. Before setting out on a campaign, you must check:

  • Whether the ballistae work - unit tests
  • Whether the legion cooperates - integration tests
  • Whether the entire fort is ready for the expedition - end-to-end tests
  • How the fort handles a storm - stress tests
  • Whether all systems work reliably - reliability tests
// Basic testing philosophy in a Roman fort
describe('application', () => {
 it('should be ready to march', () => {
 const cohort = new LegionaryCohort();
 expect(cohort.isCombatReady()).toBe(true);
 });

 it('should survive a storm', () => {
 const cohort = new LegionaryCohort();
 const storm = new Storm({ intensity: 'high' });

 expect(() => cohort.weatherStorm(storm)).not.toThrow();
 expect(cohort.status).toBe('operational');
 });
});

Types of Tests in a Roman Fort

1. Unit Tests - Testing Individual Components

It's like checking each ballista separately - whether it loads properly, fires in the right direction, and doesn't explode:

// ballista.spec.ts
describe('Ballista', () => {
 let ballista: Ballista;

 beforeEach(() => {
 ballista = new Ballista('Front Line Ballista #1');
 });

 it('should load with ammunition', () => {
 ballista.load(BoltType.IRON);
 expect(ballista.isLoaded()).toBe(true);
 expect(ballista.getAmmunitionType()).toBe(BoltType.IRON);
 });

 it('should fire when loaded', () => {
 ballista.load(BoltType.IRON);
 const result = ballista.fire();

 expect(result.hit).toBeDefined();
 expect(ballista.isLoaded()).toBe(false);
 });

 it('should not fire when not loaded', () => {
 expect(() => ballista.fire()).toThrow('Ballista not loaded!');
 });
});

2. Integration Tests - Testing Cooperation

It's like combat exercises for the entire legion - whether the ballistae cooperate with the navigation system, whether communication between the front lines works:

// cohort-combat.integration.spec.ts
describe('Legion Combat Integration', () => {
 let cohort: LegionaryCohort;
 let enemy: EnemyLegion;

 beforeEach(() => {
 cohort = new LegionaryCohort();
 cohort.addBallista(new Ballista('Left Flank #1'));
 cohort.addBallista(new Ballista('Right Flank #1'));
 enemy = new EnemyLegion();
 });

 it('should coordinate attack of all ballistae', async () => {
 const battleResult = await cohort.attackEnemy(enemy);

 expect(battleResult.shotsfired).toBe(2);
 expect(battleResult.hits).toBeGreaterThan(0);
 expect(enemy.health).toBeLessThan(enemy.maxHealth);
 });
});

3. End-to-End Tests - Full Expedition Simulation

It's like a complete campaign test - from marching out of the fort, through fighting enemies, to returning with tributes:

// tribute-hunt.e2e.spec.ts
describe('Complete Tribute Hunt', () => {
 let app: INestApplication;

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

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

 it('should conduct a complete tribute expedition', async () => {
 // 1. Plan the expedition
 const expeditionPlan = await request(app.getHttpServer())
 .post('/expeditions/plan')
 .send({
 destination: 'Tribute Island',
 legionSize: 20,
 duration: 7
 })
 .expect(201);

 // 2. Execute the expedition
 const expedition = await request(app.getHttpServer())
 .post('/expeditions/execute')
 .send({ planId: expeditionPlan.body.id })
 .expect(201);

 // 3. Check results
 expect(expedition.body.success).toBe(true);
 expect(expedition.body.tributesFound).toBeGreaterThan(0);
 expect(expedition.body.legionStatus).toBe('healthy');
 });
});

Testing Framework in NestJS

NestJS uses Jest by default - a powerful testing framework that supports all types of tests:

// package.json
{
 "scripts": {
 "test": "jest",
 "test:watch": "jest --watch",
 "test:cov": "jest --coverage",
 "test:e2e": "jest --config ./test/jest-e2e.json"
 },
 "jest": {
 "moduleFileExtensions": ["js", "json", "ts"],
 "rootDir": "src",
 "testRegex": ".*\.spec\.ts$",
 "transform": {
 "^.+\.(t|j)s$": "ts-jest"
 },
 "collectCoverageFrom": [
 "**/*.(t|j)s"
 ],
 "coverageDirectory": "../coverage",
 "testEnvironment": "node"
 }
}

Basic Testing Concepts

Test Doubles - Stand-ins in the Application

Sometimes we need to replace real components with their imitations:

// Mock - imitation of external services
const mockWeatherService = {
 getWeather: jest.fn().mockResolvedValue({
 condition: 'sunny',
 windSpeed: 15,
 temperature: 25
 })
};

// Spy - spying on method calls
const spyOnBallistaFire = jest.spyOn(ballista, 'fire');

// Stub - fixed responses
const tributeServiceStub = {
 findTribute: () => Promise.resolve(new Tribute('Golden Coin'))
};

Test Lifecycle

describe('Legionary Cohort Management', () => {
 let legion: LegionaryCohort;

 // Before all tests
 beforeAll(async () => {
 // Global configuration
 await setupTestDatabase();
 });

 // Before each test
 beforeEach(() => {
 legion = new LegionaryCohort();
 legion.addLegionary(new Legionary('Marcus Aquila', 'Centurion'));
 });

 // After each test
 afterEach(() => {
 legion.dismiss();
 });

 // After all tests
 afterAll(async () => {
 await cleanupTestDatabase();
 });

 it('should manage the cohort', () => {
 expect(legion.size()).toBe(1);
 expect(legion.getCenturion().name).toBe('Marcus Aquila');
 });
});

Testing in NestJS - Special Tools

Test Module Builder

// legion.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing';

describe('LegionService', () => {
 let service: LegionService;
 let module: TestingModule;

 beforeEach(async () => {
 module = await Test.createTestingModule({
 providers: [
 LegionService,
 {
 provide: 'LegionaryRepository',
 useValue: mockLegionaryRepository,
 },
 ],
 }).compile();

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

 afterEach(async () => {
 await module.close();
 });

 it('should recruit a new legionary', async () => {
 const legionariesData = { name: 'Aurelia Bona', rank: 'Speculator' };
 const result = await service.recruitLegionary(legionariesData);

 expect(result.name).toBe('Aurelia Bona');
 expect(mockLegionaryRepository.save).toHaveBeenCalledWith(legionariesData);
 });
});

Best Testing Practices

1. AAA Pattern - Arrange, Act, Assert

it('should calculate tribute value with tax', () => {
 // Arrange - preparation
 const tribute = new Tribute('Golden Chalice', 1000);
 const taxCalculator = new TaxCalculator();

 // Act - execution
 const totalValue = taxCalculator.calculateWithTax(tribute, 0.1);

 // Assert - verification
 expect(totalValue).toBe(1100);
});

2. Test Isolation

// Good test - independent
it('should find tribute by ID', () => {
 const tribute = tributeService.findById(1);
 expect(tribute.name).toBe('Golden Compass');
});

// Bad test - dependent on other tests
let globalTributeId;
it('should add tribute', () => {
 globalTributeId = tributeService.add(new Tribute('Ruby'));
});
it('should find added tribute', () => {
 const tribute = tributeService.findById(globalTributeId);
 expect(tribute).toBeDefined();
});

3. Descriptive Test Names

// Good name
it('should throw exception when legionary tries to pick up tribute heavier than their maximum weight', () => {
 // test
});

// Weak name
it('test lifting', () => {
 // test
});

Example of a Complete Service Test

// tribute.service.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { TributeService } from './tribute.service';
import { Tribute } from './tribute.entity';
import { Repository } from 'typeorm';

describe('TributeService', () => {
 let service: TributeService;
 let repository: Repository<Tribute>;

 const mockRepository = {
 find: jest.fn(),
 findOne: jest.fn(),
 save: jest.fn(),
 delete: jest.fn(),
 create: jest.fn(),
 };

 beforeEach(async () => {
 const module: TestingModule = await Test.createTestingModule({
 providers: [
 TributeService,
 {
 provide: getRepositoryToken(Tribute),
 useValue: mockRepository,
 },
 ],
 }).compile();

 service = module.get<TributeService>(TributeService);
 repository = module.get<Repository<Tribute>>(getRepositoryToken(Tribute));
 });

 afterEach(() => {
 jest.clearAllMocks();
 });

 describe('findAll', () => {
 it('should return an array of tributes', async () => {
 const tributes = [
 { id: 1, name: 'Golden Coin', value: 100 },
 { id: 2, name: 'Silver Ring', value: 50 },
 ];

 mockRepository.find.mockResolvedValue(tributes);

 const result = await service.findAll();

 expect(result).toEqual(tributes);
 expect(repository.find).toHaveBeenCalledTimes(1);
 });

 it('should return an empty array when no tributes exist', async () => {
 mockRepository.find.mockResolvedValue([]);

 const result = await service.findAll();

 expect(result).toEqual([]);
 expect(result.length).toBe(0);
 });
 });

 describe('create', () => {
 it('should create a new tribute', async () => {
 const tributeData = { name: 'Diamond Ring', value: 5000 };
 const expectedTribute = { id: 1, ...tributeData };

 mockRepository.create.mockReturnValue(expectedTribute);
 mockRepository.save.mockResolvedValue(expectedTribute);

 const result = await service.create(tributeData);

 expect(result).toEqual(expectedTribute);
 expect(repository.create).toHaveBeenCalledWith(tributeData);
 expect(repository.save).toHaveBeenCalledWith(expectedTribute);
 });

 it('should throw an exception for invalid data', async () => {
 const invalidData = { name: '', value: -100 };
 mockRepository.save.mockRejectedValue(new Error('Validation failed'));

 await expect(service.create(invalidData)).rejects.toThrow('Validation failed');
 });
 });
});

Testing is not just about checking whether code works - it's a guarantee that your application will survive every storm and reach its destination with the entire legion and tributes! In the following modules, we'll learn the details of different types of tests.

Code for this lesson: src/testing-intro.ts
// Testing - Introduction to Testing in the Roman Imperium
import { Test, TestingModule } from '@nestjs/testing';

// Basic structure of tests in NestJS
// Every fort element must be checked before marching!

// 1. DESCRIBE - defines test group (like fort section inspection)
describe('LegionService', () => {

  // 2. IT - single test (like checking one ballista)
  it('should be defined', () => {
    const service = new LegionService();
    expect(service).toBeDefined();
  });

  it('should return all legions', () => {
    const service = new LegionService();
    const legions = service.findAll();

    // 3. EXPECT - assertion (is the result correct?)
    expect(legions).toBeInstanceOf(Array);
    expect(legions.length).toBeGreaterThan(0);
  });

  it('should create a new legion', () => {
    const service = new LegionService();
    const newLegion = service.create({
      name: 'Legio XIII Gemina',
      soldiers: 5000,
      commander: 'Julius Caesar',
    });

    expect(newLegion).toBeDefined();
    expect(newLegion.name).toBe('Legio XIII Gemina');
    expect(newLegion.soldiers).toBe(5000);
  });
});

// Example service for testing
class LegionService {
  private legions = [
    { id: 1, name: 'Legio X Equestris', soldiers: 4800, commander: 'Pompey' },
    { id: 2, name: 'Legio IX Hispana', soldiers: 5200, commander: 'Augustus' },
  ];

  findAll() {
    return this.legions;
  }

  findOne(id: number) {
    return this.legions.find(l => l.id === id) || null;
  }

  create(data: { name: string; soldiers: number; commander: string }) {
    const legion = { id: this.legions.length + 1, ...data };
    this.legions.push(legion);
    return legion;
  }
}

// Jest matchers - inspection tools
// expect(value).toBe(expected)        - strict equality (===)
// expect(value).toEqual(expected)     - deep equality
// expect(value).toBeDefined()         - is not undefined
// expect(value).toBeTruthy()          - truthy value
// expect(value).toContain(item)       - array contains element
// expect(fn).toThrow()                - function throws error

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which types of tests do we distinguish in NestJS applications?

  2. 2. Unit tests in NestJS are used for:

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Write a test verifying the correct operation of the legions service

  • Vertical ordering

    Arrange the Jest test lifecycle from start to finish:

  • Click in order

    Arrange the correct syntax of a describe block in Jest:

  1. QuestionTypes of tests in NestJS
  2. QuestionPurpose of unit tests
  3. QuestionJest testing framework
  4. Coding taskPractice: Jest test structure
  5. Put in orderTest lifecycle
  6. Click in orderDescribe syntax in Jest

Useful articles