title: NodeJS 'assert' test fails for json object returned through the express http response
body: <p>Having recently developed an interest in NodeJS, I finally managed to get my hands on a NodeJS book. A simple example on the book was to create an express server and write a test to verify a simple API exposed as part of the exercise.</p>
  
  <p>Please refer to the following code (I am using node v0.8.8)</p>
  
  <p>The Server (nodeExample.js)</p>
  
  <pre><code>     var express = require('express')
       var app = express.createServer()
       app.listen(8000)
       var msgs = []
  
       app.get('/', function(req, res) {
          res.send('Welcome to Node Twitter')
       })
  
       app.post('/send', express.bodyParser(), function(req, res) {
          if (req.body &amp;&amp; req.body.tweet) {
             msgs.push(req.body.tweet)
             res.send({status:"ok", message:"Message received"})
          } else {
              res.send({status:"nok", message:"Message not received"})
          }
      })
  
      app.get('/tweets', function(req,res) {
      res.send(msgs)
      })
  </code></pre>
  
  <p>The Test</p>
  
  <pre><code>var http = require('http'),
  assert = require('assert')
  var opts = {
    host: 'localhost',
    port: 8000,
    path: '/send',
    method: 'POST',
    headers: {'content-type':'application/x-www-form-urlencoded'}
  }
  
  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:"Message received"})
   })
  })
  
  req.write('tweet=test')
  req.end()
  </code></pre>
  
  <p>I managed to get the server up and running without issues ( Except for a warning that the createServer method of 
  express is deprecated , although doesn't seem to be what's bothering me ) ; but when I run the test, assert throws an exception indicating test failing, which should obviously not happen.</p>
  
  <p>Here's a screenshot of the problem</p>
  
  <p><img src="https://i.stack.imgur.com/6kGv8.png" alt="enter image description here"></p>
  
  <p>If you observe the error closely it seems to be the escape characters "\n" appended in parts of the response, that seem to be causing the problem.</p>
  
  <p>I tried to circumvent the issue by</p>
  
  <ol>
  <li>trying different equality checks (equal , strictEqual and deepEqual)</li>
  <li>removing the utf8 encoding from the response</li>
  </ol>
  
  <p>but had no luck ( unless I ofcourse perform an equality check with stringified test data, against the stringified response object returned where the formatting has been manually removed ).</p>
  
  <p>So the question is,</p>
  
  <ol>
  <li>Why is the response formatted in the above manner ? Was it only for readability ?</li>
  <li>Assuming I am not allowed to remove the formatting, how can I perform an assert test on the response data I just received.</li>
  </ol>