pre

pretendr

Powerful Javascript mocking

Showing:

Popularity

Downloads/wk

2

GitHub Stars

3

Maintenance

Last Commit

6mos ago

Contributors

2

Package

Dependencies

0

Size (min+gzip)

0.8KB

License

Type Definitions

Tree-Shakeable

No?

Categories

Readme

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 () {}
});

Mock objects, accessed via the mock property (or Mock for classes), are indistinguishable from the real thing. All your observer properties/methods are on the base object.

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.ok(fs.readFile.called);
assert.equal(fs.readFile.calls[0].args[1], 'f.txt');

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

fs.readFile.calls[0].callback();
assert.ok(fs.appendFile.calledOnce);

We can set return values:

mockFs.readFileSync.returnValue("some text");
// or
mockFs.readFileSync.fake(function (filename) {
    if (filename === "f.txt") {
      return "some text";
    }
    return "other 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].instance;
assert.equal(mockRs.calls[0].args[0], "data");

If you have lots of function calls and you only want to test one of them, use findCall to find a call by it's arguments:

mockFs.findCall(['somefile.txt']).callback();

findCall can also take a number for a number of arguments, or a function which should return true for each matching argument.

Share it

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

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100
No reviews found
Be the first to rate

Alternatives

No alternatives found

Tutorials

No tutorials found
Add a tutorial