Kurzreferenz

Expect.js Assertion-Bibliothek Spickzettel

Kurzreferenz fuer Expect.js: Setup, grundlegende Assertions, verkettete Assertions und Spies mit Aufrufverifizierung.

· Veröffentlicht

Expect ist eine Assertion-Bibliothek fuer JavaScript-Anwendungen mit klarer Syntax und integrierter Spy-Unterstuetzung.

Verwendung und Installation (Usage)

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

Verfuegbare Assertions (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)

Verkettete Assertions (Chained Assertions)

Assertions koennen fliessend miteinander verkettet werden:

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()      // Leitet den Aufruf an das Original weiter
  .andCall(fn)
  .andThrow(exception)
  .andReturn(value)

Assertions fuer 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')

Verwandte Referenzen

Verwandte Themen