Answer the question
In order to leave comments, you need to log in
How to test javascript code?
Good evening dear users and readers!
I ran into such a problem that I don’t understand how to test the controller function - getTracks. The code for this function is as follows:
var Promise = require('bluebird');
var Errors = require('./errors');
var pageConditions = require('./sequelize').getPageConditions;
function getTracks(req, res, next) {
var conditions = pageConditions(req.params.page, 10);
req.requestedUser.getTracksAndCount(conditions)
.then(function(result) {
res.set('X-Total-Count', result.count);
res.set('X-Offset', conditions.offset);
res.set('X-Limit', conditions.limit);
res.json({
status: 'OK',
data: result.rows
});
})
.catch(function(err) {
next(err);
});
}
var assert = require('assert');
var sinon = require('sinon');
var Promise = require('bluebird');
var appPath = './app';
var mock = require('mock-require');
var Controller = require(appPath + '/users');
describe('User controller', function() {
describe('method `getTracks`', function() {
var controller;
var getPageConditions = sinon.stub();
beforeEach(function() {
getPageConditions = sinon.stub();
mock(appPath + '/helpers/sequelize', {
getPageConditions: getPageConditions
});
controller = Controller();
});
it('response track list if user have tracks by condition', function() {
var req = {
params: {
page: 'fakeValue'
},
requestedUser: {
getTracksAndCount: sinon.stub()
}
};
var res = {
set: sinon.spy(),
json: sinon.spy(),
};
var next;
var conditions = {
offset: 'fakeValueOffset',
limit: 'fakeValueLimit'
};
var result = {
count: 'fakeValueCount',
rows: 'fakeValueRows'
};
getPageConditions.returns(conditions);
req.requestedUser.getTracksAndCount.returns(Promise.resolve(result));
controller.getTracks(req, res, next);
assert(getPageConditions.called);
assert(req.requestedUser.getTracksAndCount.calledWith(conditions));
assert(res.set.calledWith('X-Total-Count', result.count));
assert(res.set.calledWith('X-Offset', conditions.offset));
assert(res.set.calledWith('X-Limit', conditions.limit));
});
});
});
assert(res.set.calledWith('X-Total-Count', result.count));
assert(res.set.calledWith('X-Offset', conditions.offset));
assert(res.set.calledWith('X-Limit', conditions.limit));
req.requestedUser.getTracksAndCount.returns(Promise.resolve(result));
returns a promise with the result - result and all subsequent actionsres.set('X-Total-Count', result.count);
res.set('X-Offset', conditions.offset);
res.set('X-Limit', conditions.limit);
res.json({
status: 'OK',
data: result.rows
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question