I've created a simple module that posts some data to an external service which returns a message and some other results.
Am trying to test this with Mocha but I'm finding it hard to understand how to access the returned value.
I can see it logged in the console but don't know how to set it as a variable. As you'll not doubt notice, I am a novice javacripter. I'm sure it's simple, I just can't see how.
My module:
module.exports = {
foo: function(id,serial) {
var querystring = require('querystring');
var http = require('http');
var fs = require('fs');
var post_data = querystring.stringify({
'serial' : serial,
'id': id
});
var post_options = {
host: 'localhost',
port: '8080',
path: '/api/v1/status',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log(chunk);
return chunk;
});
});
post_req.write(post_data);
post_req.end();
}
}
And I've called this with:
describe('Functions and modules', function() {
it('does some shizzle', function(done) {
var tools = require('../tools');
chunk = '';
id = 123;
serial =456;
tools.foo(id,serial);
chunk.should.equal.......
});
});
I basically need the returned message from tools.foo(id,serial) However chunk is blanker than a blank thing.
In my terminal I can see something like:
{"message":"This device is still in use","live":"nop"}
You cannot access the "returned" value the way you would in other languages. Http requests in node are asynchronous, and don't return their values. Instead, you pass in a call back function, or create a callback function within the scope of the same request. For example you could complete your function like this: (I removed some of the filler)
module.exports = {
foo: function (options, data, callback) {
'use strict';
var completeData = '';
var post_req = http.request(options, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log(chunk);
completeData += chunk;
return chunk;
});
res.on('end', function () {
callback(completeData);
//You can't return the data, but you can pass foo a callback,
//and call that function with the data you collected
//as the argument.
});
});
post_req.write(data);
post_req.end();
}
};
function someCallBackFunction (data) {
console.log("THE DATA: " + data);
}
var someOptions = "whatever your options are";
var someData = "whatever your data is";
module.exports.foo(someOptions, someData, someCallBackFunction);
If the function your defining is at the same scope, you could also access someCallBackFunction directly within the scope of foo, but passing in the callback is better style.