mercredi 30 septembre 2015

Unit testing a routes function - Node.js

I'm trying to add a unit test for the function that handles the route. My problem is that the done function should wait for the completion of the asynchronous calls but does not.

I've tried the solution that was suggested in this SO question but it did not work. I'm not sure if it matters but I am using proxyquire to stub out some of the dependencies that make requests to remote hosts and to databases. My code is below:

app.js:

var foo = require('foo');
app.get('/test', foo.test);

foo.js:

var requestPromise = require('request-promise');

module exports.test = function(req, res) {
    var options = {
        uri: 'http://ift.tt/1P51p2t',
        method: 'GET'
    }

    var promise = requestPromise(options);
    promise.then(function(response) {
        res.status(200);
        res.json(response);
    });

}

My mocha test is below:

describe("foo-test", function () {


    var login = proxyquire("foo",
        {
            "request-promise": function (url) {
                return Q.fcall(function () {
                        return {id: 'dummy_facebook_id'};
                    }
                )
            },
        }
    );

    it("Should check response after asynchronous method completes", function(done) {
        var responseSpy = {
            jsonResponse: {},
            json: function(body) {
                this.jsonResponse = body;
                done();
            },
            status: sinon.spy()

        };

        login.test("blah", responseSpy);

        console.log(responseSpy);
    });
})

I'm expecting the 'console.log' line in the test to be executed after the promise in the code being tested is executed, unfortunately that's not the case.

Aucun commentaire:

Enregistrer un commentaire