I'm trying to learn about testing promises in NodeJS, and the testing methods that I used in other languages do not suit me a bit. The main question: "How to effectively test indirect inputs and outputs in one or more then coded (and made or captured) blocks of promises?"
Here is the source lib/test.js
:
var Bluebird = require("bluebird"),
fs = Bluebird.promisifyAll(require("fs"));
function read(file) {
return fs.readFileAsync(file)
.then(JSON.parse)
.done(function () {
console.log("Read " + file);
});
}
function main() {
read("test.json");
}
if (require.main === module) {
main();
}
module.exports = read;
And here is the source tests/test.js
var Bluebird = require("bluebird"),
chai = require("chai"),
expect = chai.expect,
sinon = require("sinon"),
sandbox = sinon.sandbox.create(),
proxyquire = require("proxyquire");
chai.use(require("chai-as-promised"));
chai.use(require("sinon-chai"));
describe("test", function () {
var stub, test;
beforeEach(function () {
stub = {
fs: {
readFile: sandbox.stub()
}
}
test = proxyquire("../lib/test", stub);
});
afterEach(function () {
sandbox.verifyAndRestore();
});
it("reads the file", function () {
test("test.json");
expect(stub.fs.readFile).to.have.been.calledWith("test.json");
});
it("parses the file as JSON", function () {
stub.fs.readFileAsync = sandbox.stub().returns(Bluebird.resolve("foo"));
sandbox.stub(JSON, "parse");
test("test.json");
expect(JSON.parse).to.have.been.calledWith("foo");
});
it("logs which file was read", function () {
stub.fs.readFileAsync = sandbox.stub();
sandbox.stub(JSON, "parse");
test("bar");
expect(console.log).to.have.been.calledWith("Read bar")
});
});
I understand that these examples are trivial and inventive, but I try to understand how to test the promise chain, and not how to read the file and parse it as JSON. :)
In addition, I am not attached to any frameworks or anything like that, so if I inadvertently chose the bad one when capturing any of the included NodeJS libraries, the call will also be evaluated.
Thanks!