Question

I'm trying to test an api (sails.js) and I can't use the data returned by JSON.parse

I have this test:

describe('when requesting resource /coin', function () {

it ('should request "/Coin" on server and return it', function (done) {
  supertest(sails.express.app)
    .get('/Coin')
    .expect('Content-Type', /json/)
    .expect(200, done)
    .end(function(err, res) {
      var result = JSON.parse(JSON.stringify(res.text));
      assert.equal(result.cash, 1000);
      done();
    })
  })
 })

Here you can see how result looks like:

Uncaught TypeError: Object [

{

"userId": "macario",

"cash": 1000,

"createdAt": "2014-03-04T20:17:57.483Z",

"updatedAt": "2014-03-07T02:47:51.098Z",

"id": 15

}

][

{

"userId": "macario",

"cash": 1000,

"createdAt": "2014-03-04T20:17:57.483Z",

"updatedAt": "2014-03-07T02:47:51.098Z",

"id": 15

} ]

And the error:

Uncaught AssertionError: "undefined" == 1000

I would like to use this informations, but i can't access them.

Was it helpful?

Solution

Your response in res.text is probably a string.

When you stringify a string the quotes become escaped, resulting in this;

""[{\"userId\":\"macario\",\"cash\":1000,\"createdAt\":\"2014-03-
04T20:17:57.483Z\",\"updatedAt\":\"2014-03-07T02:47:51.098Z\",\"id\":15}]""

So when you call JSON.parse on it, it just turns it back into a String, instead of into the Object you want.

Just change this line;

var result = JSON.parse(JSON.stringify(res.text));

to this;

var result = JSON.parse(res.text);

If the parse fails then the JSON in res.text is malformed and that is your main problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top