简体   繁体   中英

Mocha Chai AssertionError: expected array to be a json

1) This first test suite case works well, throw no erros at all.

chai.request(app) .get('/api/courses') .end((err, res) => {
res.should.have.status(200);
res.body.should.be.a("json");
done(); });

2) Althought, that one says "AssertionError: expected [ Array(3) ] to be a json", even though nothing changed.

describe("Courses", () => {
describe("GET /api/courses", () => {
    it("should get all the courses", (done) => {
        chai.request(app)
             .get('/api/courses')
             .end((err, res) => {
                 res.should.have.status(200);
                 res.body.should.be.a("json");
                 done();
              });
    })
}); 

});

I literally just inserted the describe and it features to give more info about the test.

App.js

App.test.js

Image Example here

Anyways, what do you want to achieve with this test?

EDIT: Sorry, I didn't want this to be posted as an answer. But while I'm already here:

As far as I can tell, chai is working as expected, since the return value you receive is in fact an array, and not a json (albeit a json-file in NodeJs can be an array). That's why the test is failing. If you want to check the actual header of the response, you can test res.headers. Why it was working outside of the mocha test I can not tell you, but feel like it was rather a display- than an actual bug, as in how did you actually test that the assertion was properly validated?

I don't think we can check whether body is json or not using that command.

res.body.should.be.a("json"); // invalid

If you take a look at chai documentation or here , there is no way you can specify json inside a() function.

Alternative solution you can check the json from the res.headers and also you can check the response body is array or not such as

chai
  .request(app)
  .get("/api/courses")
  .end((err, res) => {
    res.should.have.status(200);

    res.body.should.be.a('array'); 
    res.headers["content-type"].should.contains('application/json');

    done();
  });

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM