Search code examples
javascriptjasminejasmine-node

jasmine-node doesnt wait for body to be done


I am currently able to pass a test with

expect(response.statusCode).toEqual(200)

but doing this line right underneath

expect(body.name).toEqual('erilcompa')

gives me a undefined. console.log(body) however gives the body

All of it looks like this:

var request = require("request");
var base_url = "http://127.0.0.1:3000/api"


 describe("Routes Suite", function(){
     var customerID;
    it("should make a quotation", function(done){

        request.post({url:base_url + '/customer', 
        form: {
          'name': 'erilcompa',
          'vatNr': '22',
        }},
        function(error,response, body){

          expect(response.statusCode).toEqual(200)
          expect(body.name).toEqual('erilcompa')
          customerID = body.name

          console.log(response.statusCode)

          done()
        })  
    })
 )}

It's probably something obvious but any help is really appreciated!!


Solution

  • You should use JSON.parse to parse the body, because the type of the body argument is string.

    var bodyObj = JSON.parse(body);
    expect(bodyObj.name).toEqual('erilcompa');
    

    Note that your server must send a well-formed JSON format object

    {"name":"erilcompa"} 
    

    Your code should be like this:

    var request = require("request"); var base_url = "http://127.0.0.1:3000/api"

    describe("Routes Suite", function(){
        var customerID;
        it("should make a quotation", function(done){
    
            request.post({url:base_url + '/customer', 
                form: {
                    'name': 'erilcompa',
                    'vatNr': '22',
                }
            },
            function(error,response, body){
                expect(response.statusCode).toEqual(200);
                var bodyObj = JSON.parse(body);
                expect(bodyObj.name).toEqual('erilcompa');
                customerID = body.name;
                console.log(response.statusCode);
                done();
            })  
        })
    )}