Simple Unit Test

Ez a szint azt jelenti, hogy tudsz önállóan egyszerű egységtesztet írni, és értően használod a Jasmine / Karma / Jest tesztelési környezetet.


✅ Példa: Egyszerű függvény egységtesztje

Tegyük fel, van egy szolgáltatásod math.util.ts:

export function add(a: number, b: number): number {
  return a + b;
}

🧪 math.util.spec.ts – Teszt

import { add } from './math.util';

describe('add()', () => {
  it('should return sum of two numbers', () => {
    expect(add(2, 3)).toBe(5);
  });

  it('should handle negative numbers', () => {
    expect(add(-2, -3)).toBe(-5);
  });

  it('should return 0 if both numbers are 0', () => {
    expect(add(0, 0)).toBe(0);
  });
});

✅ Alapok, amiket tudni kell

FogalomJelentése
describe()Egy logikai tesztcsoport
it()Egy konkrét teszt (viselkedés)
expect(val)Elvárt érték tesztelése
toBe()Pontos egyezés (===)
toEqual()Objektum egyezés

✅ Komplexebb példa: függvény mockolása

function greet(name: string): string {
  return `Hello, ${name}!`;
}

describe('greet()', () => {
  it('should greet the user by name', () => {
    expect(greet('Gábor')).toBe('Hello, Gábor!');
  });
});

🧪 Ha szolgáltatást tesztelsz

@Injectable({ providedIn: 'root' })
export class MathService {
  double(n: number): number {
    return n * 2;
  }
}
describe('MathService', () => {
  let service: MathService;

  beforeEach(() => {
    service = new MathService();
  });

  it('should double a number', () => {
    expect(service.double(4)).toBe(8);
  });
});

🧠 Összefoglalás

Mit jelent a leírt szint?

✅ Képes vagy:

  • saját .spec.ts fájlt írni
  • egyszerű függvényeket tesztelni
  • describe, it, expect, toBe, toEqual használatára
  • a megfelelő importokat beírni (import { MyFn } from ...)
  • ng test futtatás után értelmezni, ha piros → tudod, mi a hiba

Ha szeretnél, adok gyakorlós feladatokat unit tesztre Angular service vagy pipe szinten is.

Was this page helpful?