DEV Community

Lam
Lam

Posted on

2 2

Expect.Js Cheat Sheet

References

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.getLastCall().arguments).toEqual(...)
Enter fullscreen mode Exit fullscreen mode
expect(spy).toHaveBeenCalled()
expect(spy).toHaveBeenCalledWith('some', 'args')
Enter fullscreen mode Exit fullscreen mode

Spies

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

Chaining assertions

expect(3.14)
  .toExist()
  .toBeLessThan(4)
  .toBeGreaterThan(3)
Enter fullscreen mode Exit fullscreen mode

Assertions can be chained.

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)
Enter fullscreen mode Exit fullscreen mode

Also: toNotBe, toNotEqual, etc for negatives.

Using

npm install --save-dev expect
Enter fullscreen mode Exit fullscreen mode

{: .-setup}

// using ES6 modules
import expect, { createSpy, spyOn, isSpy } from 'expect'
Enter fullscreen mode Exit fullscreen mode
// using CommonJS modules
var expect = require('expect')
var createSpy = expect.createSpy
var spyOn = expect.spyOn
var isSpy = expect.isSpy
Enter fullscreen mode Exit fullscreen mode

Expect is a library for assertions in tests.
See: mjackson/expect

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay