expect (js) not working inside superagent (js)

435 views Asked by At

I'm trying to do TDD for the Rest APIs that I've been creating. New to NodeJS.

I've created a Rest API, and on the response I want to perform all the expect checks. To make an HTTP request I'm using SuperagentJS (also tried RequestJS).

Here is how my code looks like (Snippet only, not whole code)

var expect = require("chai").expect;
var request = require("superagent");

describe("Creation of New Entity", function(){
    it("Create a New Entity", function(){
        request
            .get("http://localhost")
            .end(function(err, httpResponse){
                expect("1234").to.have.length(3);//equals(500);
                expect(200).to.equals(200);
        });
    });
});

No matter what I try, mocha always gives successful result. (All test cases passed)

Please tell what I'm missing here. What should I do to implement test cases on httpRespnse. I'm sure that request is working fine, because whenever I use console.log(httpResponse.text), it is returning the default apache home page.

1

There are 1 answers

2
Peter Lyons On BEST ANSWER

All networking in node.js is asynchronous, therefore you must use the mocha asynchronous flavor of it("Create a New Entity", function(done) { and call the done callback when your test is done.

var expect = require("chai").expect;
var request = require("superagent");

describe("Creation of New Entity", function(){
    it("Create a New Entity", function(done){
        request
            .get("http://localhost")
            .end(function(err, httpResponse){
                expect(err).not.to.exist();
                expect("1234").to.have.length(3);//equals(500);
                expect(200).to.equals(200);
                done()
        });
    });
});