Szybka pomoc

Ściągawka z testów Jasmine BDD

Szybki przewodnik po frameworku testowym Jasmine: describe, it, matchery, szpiegi (spies), testy asynchroniczne oraz haki beforeEach/afterEach.

· Opublikowano

Jasmine to framework BDD (Behavior-Driven Development) do testowania kodu JavaScript bez zewnętrznych zależności od DOM.

Struktura testów i składnia BDD

describe('Calculator', () => {
  let calc;

  beforeEach(() => {
    calc = new Calculator();
  });

  afterEach(() => {
    calc.cleanup();
  });

  it('should add two numbers correctly', () => {
    expect(calc.add(2, 3)).toBe(5);
  });

  xit('temporarily skipped test', () => {
    // pending
  });
});

Matchery

expect(val).toBe(true);              // Strict equality (===)
expect(val).toEqual({ a: 1 });       // Deep object equality
expect(val).toMatch(/regex/);        // Regular expression match
expect(val).toBeDefined();           // Not undefined
expect(val).toBeUndefined();         // Is undefined
expect(val).toBeNull();              // Strict null
expect(val).toBeTruthy();            // Truthy coercion
expect(val).toBeFalsy();             // Falsy coercion
expect(arr).toContain('item');       // Array or string inclusion
expect(val).toBeLessThan(10);        // Numeric comparisons
expect(val).toBeGreaterThan(5);
expect(fn).toThrow();                // Exception thrown
expect(fn).toThrowError(TypeError);

Odwróć dowolny matcher za pomocą .not:

expect(val).not.toBeNull();

Szpiegi (Spies) i mocki

// Spy on an existing object method
spyOn(service, 'fetchData').and.returnValue(Promise.resolve([1, 2]));

service.fetchData('users');

expect(service.fetchData).toHaveBeenCalled();
expect(service.fetchData).toHaveBeenCalledWith('users');
expect(service.fetchData.calls.count()).toBe(1);

// Create standalone anonymous spy
const callback = jasmine.createSpy('myCallback');
callback('payload');
expect(callback).toHaveBeenCalledWith('payload');

Testy asynchroniczne

it('fetches async data', async () => {
  const result = await fetchItems();
  expect(result.length).toBeGreaterThan(0);
});

Źródła

Powiązane tematy