Riferimento rapido

Foglio di riferimento Expect.js Assertions

Guida di riferimento rapida per la libreria di asserzioni Expect.js: setup, asserzioni di base, asserzioni concatenate e spies con verifica delle chiamate.

· Pubblicato

Expect e una libreria di asserzioni per JavaScript con una sintassi pulita e supporto integrato per gli spies.

Uso e installazione (Usage)

npm install --save-dev expect
// Utilizzo con moduli ES6
import expect, { createSpy, spyOn, isSpy } from 'expect'
// Utilizzo con moduli CommonJS
var expect = require('expect')
var createSpy = expect.createSpy
var spyOn = expect.spyOn
var isSpy = expect.isSpy

Elenco delle asserzioni (Assertions)

expect(x).toBe(y)
  .toBe(val)
  .toEqual(val)
  .toThrow(err)
  .toExist()          // aka: toBeTruthy()
  .toNotExist()       // aka: toBeFalsy()
  .toBeA(constructor)
  .toBeA('string')
  .toMatch(/expr/)
  .toBeLessThan(n)
  .toBeGreaterThan(n)
  .toBeLessThanOrEqualTo(n)
  .toBeGreaterThanOrEqualTo(n)
  .toInclude(val)     // aka: toContain(val)
  .toExclude(val)
  .toIncludeKey(key)
  .toExcludeKey(key)

Asserzioni concatenate (Chained Assertions)

Le asserzioni possono essere concatenate in modo fluido:

expect(3.14)
  .toExist()
  .toBeLessThan(4)
  .toBeGreaterThan(3)

Spies (Spies)

const video = {
  play: function () { /* ... */ }
}
spy = expect.spyOn(video, 'play')
spy = expect.spyOn(video, 'play')
  .andCallThrough()      // Inoltra la chiamata alla funzione originale
  .andCall(fn)
  .andThrow(exception)
  .andReturn(value)

Asserzioni sugli Spies (Assertions on Spies)

expect(spy.calls.length).toEqual(1)
expect(spy.calls[0].context).toBe(video)
expect(spy.calls[0].arguments).toEqual([ 'some', 'args' ])
expect(spy).toHaveBeenCalled()
expect(spy).toHaveBeenCalledWith('some', 'args')

Riferimenti correlati

Argomenti correlati