vendredi 29 avril 2016

Mocha Test for NodeJS Function not calling Callback

I have a function that sends a message to a facebook user using a facebook page.

// send text message to an user
function sendTextMessage(sender, text, callback) {
    messageData = {
        text: text
    }
    request({
        url: 'http://ift.tt/1Q7nDgi',
        qs: { access_token: token },
        method: 'POST',
        json: {
            recipient: { id: sender },
            message: messageData,
        }
    }, function (error, response, body) {
        if (error) {
            console.log('Error sending message: ', error);
            callback(-1);
        } if (response.body.error) {
              console.log('Error: ', response.body.error);
              return -2;
          } else{
            console.log('Ok: ' + JSON.stringify(body));
            callback(1);
            return response;
        }

    });
}

My problem is, when I run this code on command line, it works fine, however, I'm trying to create a test for this using mocha.

it('Text Message', function(){
    var fb_answer = function(res){
      // first schema to be compared
      var fbTextAnswerSchema = {
        "title": "fb answer schema v1",
        "type": "object",
        "required": ["recipient_id", "message_id"],
        "recipient_id": {
           "type": "string"
        },
        "message_id": {
           "type": "string"
        }
      };
      expect(res).to.be.jsonSchema(fbTextAnswerSchema);
    }
    messenger.sendTextMessage(sender, "[TEST] Testing send text message", fb_answer);
  });

And when I run mocha on command line calling this test, it not only pass, but it also does not print the body of the response.

Basically what is weird here is that, when I run using node the code print the response, and when I run with mocha, it doesn't, which makes me think that the callback of the request is not been called...

I need to pass a test function as callback to this function in order to treat the response.

Why isn't the response been print? And why the callback is not been called? Is there a better way to test this kind of function?

Thanks in advanced.

Aucun commentaire:

Enregistrer un commentaire