Ruff 1.2.0 Documentation


Ruff Mock#

Ruff Mock is a stub/mock framework in order to create mock/stub and verification.

The API of Ruff Mock is not yet stable and subject to change in the near future.

Usage#

var mock = require('ruff-mock');

Stub#

var mock = require('ruff-mock');

var when = mock.when;
var whenever = mock.whenever;

var target = {
    get: function () {
        return 'biu';
    }
};

// Mock an object, true indicates it accepts mocking methods that does not exit on the object.
var mocked = mock(target, true);

// Stub
when(mocked)
    .get('foo')
    .thenReturn('bar');

mock.get('foo'); // 'bar'
mock.get('foo'); // 'biu'

whenever(mocked)
    .get('foo')
    .thenReturn('bar');

mock.get('foo'); // 'bar'
mock.get('foo'); // 'bar'

Any Mock#

var mock = require('ruff-mock');

var mockAny = mock.mockAny;
var when = mock.when;

var mocked = mockAny();

when(mocked)
    .get('foo')
    .thenReturn('bar');

mock.get('foo'); // 'bar'

Arguments Matching#

var assert = require('assert');
var mock = require('ruff-mock');

var when = mock.when;
var any = mock.any;

var mocked = mock({}, true);

when(mocked)
    .get(any, Function)
    .then(function (name, callback) {
        assert.equal(name, 'foo');
        callback(undefined, 'bar');
    });

mocked.get('foo', function (error, result) {
    assert.ifError(error);
    assert.equal(result, 'bar');
});

Verifying#

var mock = require('ruff-mock');

var verify = mock.verify;

var mocked = mock([]);

mocked.push('foo');

verify(mocked).push('one');

Ruff mock provides some default verification mode:

  • once: make sure the target function has been invoked only once.
  • twice: make sure the target function has been invoked only twice.
  • times: you can specify how many times the target function has been invoked.
  • atLeast: how many times the target function has been invoked at least.
  • atMost: how many times the target function has been invoked at most.
  • never: making sure interaction(s) never happened.