Introduction
Testing helps catch mistakes early so the app works as expected. It makes sure changes don't break things.
Testing helps catch mistakes early so the app works as expected. It makes sure changes don't break things.
describe('MyService', () => { it('should do something', () => { expect(true).toBe(true); }); });
describe groups related tests.
it defines a single test case.
describe('CalculatorService', () => { it('adds two numbers', () => { expect(1 + 2).toBe(3); }); });
describe('UserService', () => { it('returns user by id', () => { const user = { id: 1, name: 'Anna' }; expect(user.id).toBe(1); }); });
This test checks that the getHello method of AppService returns the string 'Hello World!'. It uses NestJS testing utilities to create a test module and get the service instance.
import { Test, TestingModule } from '@nestjs/testing'; import { AppService } from './app.service'; describe('AppService', () => { let service: AppService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [AppService], }).compile(); service = module.get<AppService>(AppService); }); it('should return hello message', () => { expect(service.getHello()).toBe('Hello World!'); }); });
Write small tests that check one thing at a time.
Run tests often to catch errors early.
Use descriptive test names to understand what is tested.
Testing helps find bugs before users do.
It makes your app more reliable and easier to maintain.
Use NestJS testing tools to write clear and simple tests.
test function to define tests.test is the valid Jest function; others are invalid.describe('MathService', () => {
it('adds two numbers', () => {
const result = 2 + 3;
expect(result).toBe(5);
});
});describe('AppService', () => {
it('should return hello', () => {
const message = appService.getHello();
expect(message).toBe('Hello World');
});
});appService is not defined anywhere.appService is used but not declared or imported anywhere.Pass the test and this pattern moves unknown