mardi 6 octobre 2015

Testing promises in NodeJS

I'm trying to learn about testing promises in NodeJS, and testing methodologies that I've used in other languages are failing me a bit here. The basic question is "how do I effectively test indirect inputs and outputs in one or more chained then (and done or catch) promise blocks?"

Here the source of 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's the source of 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 realize that these examples are trivial and contrived, but I'm looking to try and understand how to test promise chains, not how to read a file and parse it as JSON. :)

Also, I'm not tied to any frameworks or anything like that, so if I inadvertently chose poorly when grabbing any of the included NodeJS libraries, a call-out would be appreciated as well.

Thanks!

Aucun commentaire:

Enregistrer un commentaire