fscore fscore - 7 months ago 87
Javascript Question

Uncaught TypeError: Cannot read property 'total' of undefined

I get a JSON from my response object so I do:

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


I print the JSON and get JSON back. But when I retrieve the value inside
json.body.value.total
then it gives this error:

Uncaught TypeError: Cannot read property 'total' of undefined


I have no idea why. I pasted the value that receive from var json and printed on console and was able to retrieve total. But I cannot do it through the code. There is a JSON value total. Its just unable to recognize. On the console, it works but does not work in the code.

I get JSON back from my response object which I retrieve using
response.text
. I think it needs to change in parsable object but all it returns is
undefined


it('returns http 200', function (done) {
chai
.request(baseUrl)
.get('/api/')
.set('Authorization', 'Basic abc')
.query({val:'hey'})
.end(function(err, res) {
expect(res).to.have.status(200);

var json = res.text;

console.log('val: '+ JSON.parse(json.body));
var val = json.body.value.total; //undefined
expect(val.to.be.above(0)); //fails
done();
});
});

Answer

The REST API that I built was returning the response.body but what worked is this:

var body = JSON.parse(json.body);
var obj = JSON.stringify(body);
var jsonObj = JSON.parse(obj);

The above looks ridiculous but thats what worked. json -> object -> json. It was finding trouble to figure out that its a json object.

The console was doing a good job but not the library that I was using.

The complete code is this:

it('returns http 200', function (done) {
        chai
        .request(baseUrl)
        .get('/api/')
        .set('Authorization', 'Basic abc')
        .query({val:'hey'})
        .end(function(err, res) {
            expect(res).to.have.status(200);

            var json = res.text;

            var body = JSON.parse(json.body);
            var obj = JSON.stringify(body);
            var jsonObj = JSON.parse(obj);
            var val = jsonObj.body.value.total;
            expect(val.to.be.above(0));
            done();
        });
    });