Riferimento rapido

Cheat Sheet sui Test Jasmine BDD

Guida rapida al framework di test Jasmine: describe, it, matcher, spy, test asincroni e hook beforeEach/afterEach.

· Pubblicato

Jasmine è un framework BDD (Behavior-Driven Development) per testare codice JavaScript senza dipendenze esterne dal DOM.

Struttura dei test e sintassi 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
  });
});

Matcher

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);

Inverti qualsiasi matcher con .not:

expect(val).not.toBeNull();

Spy e funzioni Mock

// 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');

Test asincroni

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

Riferimenti

Argomenti correlati