Skip to content

m(icro)spy is a simple test spy implementation written in es6+

License

Notifications You must be signed in to change notification settings

ivoputzer/m.spy

Repository files navigation

m.spy

m(icro)spy is a simple test spy implementation written in es6+

travis dependencies coverage status linter

node version license minzip downloads

What is a test spy?

A test spy is a function that records arguments and thrown exceptions (if any) for all its calls.

Creating a spy as an anonymous function

The spy won’t do anything except record information about its calls. A common use case for this type of spy is testing how a function handles a callback:

const { strictEqual } = require('assert')
const EventEmitter = require('events')
const {spy} = require('m.spy')

test('calls listeners on event', () => {
  const callback = spy()
  const emitter = new EventEmitter()

  emitter.on('event', callback)
  emitter.emit('event')

  strictEqual(callback.called, true)
})

test('wraps the function transparently', () => {
  const sayHello = () => 'hello'
  const sayHelloSpy = spy(sayHello)

  const result = sayHelloSpy()

  strictEqual(result, 'hello')
  strictEqual(sayHelloSpy.returned('hello'), true)
})

spy.called

Is true if the spy was called at least once.

spy.notCalled

Is true if the spy was not called.

spy.callCount

The number of recorded calls.

spy.args

Array of arguments received, spy.args[0] is an array of arguments received in the first call.

spy.calledWith(arg1[, arg2[, ...]])

Returns true if spy was called at least once with the provided arguments. Can be used for partial matching, only provided arguments are checked against the actual arguments.

spy.returned(arg1)

Returns true if spy returned the provided value at least once. Uses deep comparison for objects and arrays.

About

m(icro)spy is a simple test spy implementation written in es6+

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published