tomato
tomato

Reputation: 21

mocha use chai test object equality doesnt work as expected

I'm using "chai" to test a response data of https,the data is like is:

let req = https.request(options, (res) => {
    res.on('data', (data) => {
        return callback(null, data);
    });
});

The test code like this:

let chai = require("chai");
let expect = chai.expect;
console.log("data=" + data);
console.log("typeof data = " + typeof(data));//object
console.log("util.isObject(data) = " + util.isObject(data));//true
console.log("util.isString(data) = " + util.isString(data));//false
        // assert.isObject(data, "object");
expect(JSON.stringify(data)).to.be.an("string");//ok
expect(JSON.parse(data)).to.be.an("object");//ok
expect(data).to.be.an("object");//error

Mocha test failed at "expect(data).to.be.an("object");",log like this:

data={"data":{"isDulp":false,"bindTb":false},"req_id":"REQ_APP-1487212987084_2851"}
typeof data = object
util.isObject(data) = true
util.isString(data) = false

Uncaught AssertionError: expected <Buffer 7b 22 64 61 74 61 22 3a 7b 22 69 73 44 75 6c 70 22 3a 66 61 6c 73 65 2c 22 62 69 6e 64 54 62 22 3a 66 61 6c 73 65 7d 2c 22 72 65 71 5f 69 64 22 3a 22 ... > to be an object

I thought 'data' is a object, and when I use typeof to test it, it print "object", but when I use chai "expect(data).to.be.an("object")" the test case failed. If I use "expect(JSON.parse(data)).to.be.an("object")", the test case passed. Some one who can tell me why? What the type of the 'data'?

Upvotes: 1

Views: 559

Answers (1)

Klaaz0r
Klaaz0r

Reputation: 21

The expected buffer result shows that your endpoint returns a buffer instead of an object, assert String works because it is an string of course. I am guessing that the reason it fails is that data is not an object but a buffer.

Upvotes: 1

Related Questions