Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Powerful Javascript mocking
JavaScript
Branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
test
.gitignore
.jscsrc
.travis.yml
Gruntfile.js
README.md
package.json

README.md

pretendr

Powerful JavaScript mocking

travis build status

Install it

npm install pretendr.

Use it

var pretendr = require('pretendr');

Mock your objects. You can pass in real objects (pretendr(require("fs"))) but I prefer to keep mocks to a minimum so I know exactly what my code is doing.

var mockFs = pretendr({
    appendFile : function () {},
    createReadStream : function () {},
    readFile : function () {},
    readFileSync : function () {}
});

Each function creates a mock function and each object creates a mock object. (As a shortcut, pretendr() creates a standalone mock function which you can use as a dummy callback.)

mockFs now contains a mock property, which is what you pass in to your code for testing as a substitute for the real thing. This is virtually indistinguishable to your code from the object you are mocking.

var fs = mockFs.mock;
fs.readFile('f.txt', cb);
fs.readFileSync('f.txt');

It works well with injectr, which allows you to pass in your mocks when testing.

var myLib = injectr("../lib/mylib.js", {
    fs : mockFs.mock
});

Or you can use whichever dependency injection method you're used to.

Now let's monitor the calls:

assert.equal(fs.readFile.calls[0].args[1], 'f.txt');
assert.equal(fs.appendFile.calls.length, 0);

And run the callback, then test that it did what we expect:

fs.readFile.calls[0].callback();
assert.equal(fs.appendFile.calls.length, 1);

We can set return values:

mockFs.readFileSync.returnValue("some text");
// or
mockFs.readFileSync.fake(function () {
    // arguments and context are correctly passed to this function
    return "some text";
});

Templates allow you to create a new pretendr object each time the function is run:

mockFs.createReadStream.template({
    on : function () {}
});

Then retrieve your created pretendr:

var mockRs = mockFs.createReadStream.calls[0].pretendr;
assert.equal(mockRs.calls[0].args[0], "data");

Share it

pretendr is under the MIT License. Fork it. Modify it. Pass it around.

Something went wrong with that request. Please try again.