Let's set up a test scenario:
An authenticated user wants to update the description of a 'module' attribute. The 'module' data is not stored in a database but rather defined in a required file.
Below is the test code that needs fixing:
First, we have a helper function for logging in: //app.spec.js
var login = function(done) {
var options = {
uri: 'http://localhost:3000/login'
, method: 'POST'
, form: {
username: 'user'
, password: 'ffff'
}
}
request(options, function() {
done();
});
};
Followed by the actual test case:
it('should be able to change the description of a module', function(done){
login(done);
var options = {
uri: 'http://localhost:3000/module/1'
, method: 'POST'
, form: {
desc: 'test'
}
}
request(options, function(err, res, body){
var modules = require('../Model/module').modules;
console.log(modules);
expect(modules[0].desc).toBe('test');
done();
});
});
Lastly, here's the endpoint logic in app.js:
app.post('/module/:module_id', ensureAuthenticated, function(req, res) {
var desc = req.body['desc'];
if(req.module_id){
findModuleById(req.module_id, function(err, module) {
module.desc = desc;
console.log('changed module');
console.log(module);
});
}
res.redirect('/');
});
The issue arises when checking console.log(modules) from app.post as it reflects the correct value 'test', but the test still fails with the default value.
If anyone familiar with writing tests in express/node has any suggestions, please do share. Your insight would be greatly appreciated.
P.S. Here are the current module details:
//Model/module.js
var modules = [
{id: 1, desc: 'Default description for module 1'}
, {id: 2, desc: 'Default description for module 2'}
, {id: 3, desc: 'Default description for module 3'}
];
module.exports.modules = modules;