クイックリファレンス

Expect.js アサーションライブラリ チートシート

Expect.jsアサーションライブラリのクイックリファレンス:導入方法、基本アサーション、チェーンアサーション、呼び出し検証付きスパイ機能。

· 公開日

Expect は、洗練された構文とスパイ機能を備えたJavaScript向けのアサーションライブラリです。

インストールと使用方法(Usage)

npm install --save-dev expect
// ES6 モジュールでのインポート
import expect, { createSpy, spyOn, isSpy } from 'expect'
// CommonJS での読み込み
var expect = require('expect')
var createSpy = expect.createSpy
var spyOn = expect.spyOn
var isSpy = expect.isSpy

アサーション一覧(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)

チェーンアサーション(Chained Assertions)

複数のアサーションをメソッドチェーン形式で直感的に記述できます:

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

スパイ機能(Spies)

const video = {
  play: function () { /* ... */ }
}
spy = expect.spyOn(video, 'play')
spy = expect.spyOn(video, 'play')
  .andCallThrough()      // 元の実装をそのまま呼び出す
  .andCall(fn)
  .andThrow(exception)
  .andReturn(value)

スパイのアサーション(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')

関連リファレンス

関連テーマ