Jasmine est un framework de développement piloté par le comportement (BDD) pour tester du code JavaScript sans dépendance externe au DOM.
Structure des tests et syntaxe 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
});
});
Matchers
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);
Inversez n'importe quel matcher avec .not :
expect(val).not.toBeNull();
Espions (Spies) et fonctions simulées
// 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');
Tests asynchrones
it('fetches async data', async () => {
const result = await fetchItems();
expect(result.length).toBeGreaterThan(0);
});
Références
- Documentation Jasmine
- Aide-mémoire Jest (Jest adopte une syntaxe BDD inspirée de Jasmine)