KindOfGuy KindOfGuy - 4 months ago 14
Javascript Question

Test functions ineffective

I'm using a promise to wait on a Facebook API response in the middle of a Mocha test. I'm wondering why the

expect
function is not actually checking that the data is included in the response.

I see
resolve
in the console, suggesting the graph call worked and the promise resolved, but the test passes, even though the event does not include the random data in the
expect(data).to.include
statement. How can I get test the response when the promise resolves?

var promise = new Promise(function(resolve, reject) {
var eventFB1 = graph.get('132166232459578/posts',
{limit: 1,
access_token: 't0k3n'
});

if (typeof eventFB1 !== 'undefined') {
resolve(eventFB1);
console.log('resolve');
}
else {
reject(Error("It broke"));
console.log('reject');

}
});

return promise.then(function(data) {
expect(data).to.include( 'Event name: Testing London eveng 23498723rstni' );
console.log(data);
});

Answer

You need to pass in done as an argument to your test and then call it in your "then" method. The done argument tells mocha that the specified test is finished.

it('should have the included string for data', (done) => { // <-- add done as argument
  var promise = new Promise(function(resolve, reject) {
    var eventFB1 = graph.get('132166232459578/posts',
    {
      limit: 1,
      access_token: 't0k3n'
    });

    if (typeof eventFB1 !== 'undefined') {
      resolve(eventFB1);
      console.log('resolve');
    }
    else {
      reject(Error("It broke"));
      console.log('reject');
    }
  });

  return promise
    .then(function(data) {
      expect(data).to.include( 'Event name: Testing London eveng 23498723rstni' );
      console.log(data);
      done(); // <-- call done 
    });
}

If your test throws an error and done is not called in the catch block, your test will hang and time out after 2 seconds.

Comments