Snabbreferens

Expect.js Assertions Lathund

Snabbreferens foer Expect.js: installation, grundlaggande assertions, kedjade assertions samt spies med anropsverifiering.

· Publicerad

Expect ar ett assert-bibliotek foer JavaScript-applikationer med ren syntax och inbyggt stod foer spies.

Anvandning och installation (Usage)

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

Lista over 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)

Kedjade assertions (Chained Assertions)

Assertions kan kedjas samman pa ett smidigt och flytande satt:

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()      // Vidarebefodrar anropet till originalfunktionen
  .andCall(fn)
  .andThrow(exception)
  .andReturn(value)

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

Relaterade referenser

Relaterade ämnen