Cheat Sheet速查表
跳转到主要内容

expect.js 速查表

本文根据 Devhints / expect.js 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2017-09-02。

使用方法

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

Expect 是一个用于测试断言的库。参见: mjackson/expect

断言

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)

此外: toNotBe, toNotEqual,以及用于否定判断的断言等。

链式断言

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

断言可以进行链式调用。

侦探(Spies)

const video = {
  play: function () { ··· }
}
spy = expect.spyOn(video, 'play')
spy = expect.spyOn(···)
  .andCallThrough()      // pass through
  .andCall(fn)
  .andThrow(exception)
  .andReturn(value)

针对侦探(Spies)的断言

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

参考资料