I am trying to create a node module to grab some posts but I am getting an undefined error.
Index.js
var request = require('request');
function getPosts() {
var options = {
url: 'https://myapi.com/posts.json',
headers: {
'User-Agent': 'request'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
return JSON.parse(body);
}
}
request(options, callback);
}
exports.posts = getPosts;
test/index.js
var should = require('chai').should(),
myModule = require('../index');
describe('Posts call', function () {
it('should return posts', function () {
myModule.posts().should.equal(100);
});
});
What am I missing?
=== edited after the typo was corrected ===
Looks like you don't actually "get" how callbacks work.
The callback you defined will fire asynchronously, so it can't actually be used to return a value the way you're trying to. The way to do it is to have your getPosts() function actually accept another function to it, which is the callback that the calling code cares about. So your test would look something like this:
then your module code would be something like this, in order to support that:
There could be better error handling in there, like making sure the
JSON.parse
works right, but that should give you the idea.