I'm working my way through an example using Nodejs & Express. When trying it I get an error.
A portion of the main file:
app.post('/send', express.bodyParser(), function(req, res) {
if(req.body && req.body.tweet) {
tweets.push(req.body.tweet);
res.send({status:"ok",message:"Tweet received"});
} else {
res.send({status: "nok", message: "No tweet received"});
}
});
A portion of the test script:
var req = http.request(opts, function(res) {
res.setEncoding('utf8');
var data = "";
res.on('data', function(d) {
data += d;
});
res.on('end', function() {
assert.strictEqual(data, '{"status":"ok","message":"Tweet received"}');
});
});
This is the error:
assert.js:104
throw new assert.AssertionError({
^
AssertionError: "{\n \"status\": \"ok\",\n \"message\": \"Tweet received\"\n}" === "{\"status\":\"ok\",\"message\":\"Tweet received\"}"
at IncomingMessage.<anonymous> (/home/jfb/Documents/Info/Nodejs/Up_and_Running/test.js:19:11)
at IncomingMessage.EventEmitter.emit (events.js:115:20)
at IncomingMessage._emitEnd (http.js:366:10)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
at Socket.socketOnData [as ondata] (http.js:1356:20)
at TCP.onread (net.js:404:27)
I checked my file with an editor set to display special characters and there were no newline characters as shown by the error message.
Could someone tell me what is happening here.
Thanks, Jim
You're sending an object in your response, which gets encoded into an actual JSON string by Express. Apparently Express adds some indentation in the formatting of the JSON string, which is perfectly valid. Your assertion tests that the JSON string is exactly the same as the actual Javascript source code that defines your original object; this is not something that can ever be guaranteed by any JSON encoder, as Express only sees your object but can never see the code that generates it and the presence or absence of meaningless whitespace in that code. In your tests, you should actually decode the JSON into a native object and deep-compare the resulting object with another object containing your expected state. The other option is to actually send a string instead of an object in the response; this way you can control the exact string representation of your response and not rely on external JSON encoding. This is very inflexible and gains you nothing in terms of testing.