Testing Bluebird Promises with Nodejs Vows (BDD)

662 Views Asked by At

I'm having trouble with how to properly structure a test for my Promise-returning API with Vows, e.g.

topic:function() { return myfunc() { /* returns a Bluebird Promise */ } },
'this should keep its promise':function(topic) {
    var myfunc = topic;
    myfunc()
        .then(function(result) {
            assert(false);
        })
        .catch(function(error) {
            assert(false);
        })
        .done();
}

My vow never fails. This is my first attempt at using vows to test promises. Hoping someone familiar with this will lend a hand.

In advance, thank you.

Enrique

2

There are 2 best solutions below

1
On

The following example is using a when js style promise with vows. You should be able to adapt it to whatever flavor of promise you are using. The key points are:

1) Make sure you call this.callback when your promise resolves. I assign 'this' to a variable in the example below to make sure it is properly available when the promise resolves.

2) Call this.callback (see below how this is done with the variable) with an err object and your result. If you just call it with your result, vows will interpret it as an error.

  vows.describe('myTests')
  .addBatch({
  'myTopic': {
    topic: function() {
      var vow = this;
      simpleWhenPromise()
        .then(function (result) {
          vow.callback(null, result);
        })
        .catch(function (err) {
          vow.callback(result, null);
        });
    },
    'myTest 1': function(err, result) {
      // Test your result
    }
  },
})
0
On

Since unlike libraries like Mocha - Vows does not yet have support for testing promises, we use its regular asynchronous test format that takes callbacks:

topic:function() { return myfunc() { /* returns a Bluebird Promise */ } },
    'this should keep its promise':function(topic) {
    var myfunc = topic;
    myfunc() // call nodeify to turn a promise to a nodeback, we can chain here
        .nodeify(this.callback); // note the this.callback here
}

Here is how it would look with mocha:

describe("Promises", function(){
   it("topics", function(){
       return myfunc(); // chain here, a rejected promise fails the test.
   });
})