dimanche 22 février 2015

Testing express route methods

I'm trying to check whether res.json() is being called in a express get method.


However in my get method it waits for a promise before executing res.json();


Here is the controller method:



function get(req, res, next) {

Service
.doImportantThings()
.then(success, error);

function success(result) {
res.json(result); // Method i want to test.
}

function error(error) {
// Handles it
}
}


Service:



function doImportantThings() {
var deferred = q.defer();

doStuff
.then(success, error);

function success(results) {
deferred.resolve(output);
}

function error() {
deferred.reject();
}

return deferred.promise;
}


Test:



beforeEach(function () {
var Service = require('../../../../app/services/service');
ServiceMock = sinon.mock(Service);
methodExpect = ServiceMock.expects('doImportantThings').returns(q.resolve("test"));
res.json = sinon.spy();

expressController = require('../../../../app/controllers/v1/controller');
});

afterEach(function() {
ServiceMock.restore();
});

describe('get()', function () {

it('should call res.json() one time', function () {
expressController.get(req, res);
expect(res.json).to.have.been.calledOnce; // Fails
});

it('should call res.json() with object argument.', function () {
expressController.get(req, res)
expect(res.json).to.have.been.calledWith("test"); // Fails


});

});


Because i'm using promises the expect always returns false. I've tried to use mocha's done() callback with no success. I have also tried to put a callback as a controller parameter and call done from there or do the expect there but the test either times out or doesn't assert.


All the answers i have found talk about using supertest which would probably work but i want to be able to test this without making a http request to the resource to do it.


Aucun commentaire:

Enregistrer un commentaire