KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I want to test a asynchronous javascript function that runs in node.js and makes a simple request to a http api: const HOST = 'localhost'; const PORT = 80; http = require('http'); var options = { host: HOST, port: PORT, path: '/api/getUser/?userCookieId=26cf7a34c0b91335fbb701f35d118c4c32566bce', method: 'GET' }; doRequest(options, myCallback); function doRequest(options, callback) { var protocol = options.port == 443 ? https : http; var req = protocol.request(options, function(res) { var output = ''; res.setEncoding('utf8'); res.on('data', function(chunk) { console.log(chunk); output += chunk; }); res.on('error', function(err) { throw err; }); res.on('end', function() { var dataRes = JSON.parse(output); if(res.statusCode != 200) { throw new Error('error: ' + res.statusCode); } else { try { callback(dataRes); } catch(err) { throw err; } } }); }); req.on('error', function(err) { throw err; }); req.end(); } function myCallback(dataRes) { console.log(dataRes); } Executed this code works and the response will be displayed as expected. If I execute this in a mocha test the request is not executed: describe('api', function() { it('should load a user', function() { assert.doesNotThrow(function() { doRequest(options, myCallback, function(err) { if (err) throw err; done(); }); }); assert.equal(res, '{Object ... }'); }); }); The Problem is, that no code after: var req = protocol.request(options, function(res) { is executed not even a simple cons
Tags (comma-separated)
Save Edits
Cancel