Thursday, November 7, 2013

Check to see if two JavaScript promises are the same promise in mocha testing with strictly equals.

var widget;
 
describe("when refresh is called back to back", function() {
   before(function() {
      widget = new LogViewer();
   });
 
   it("should not double load data", function() {
      var firstPromise = widget.refresh();
      var secondPromise = widget.refresh();
      assert.isTrue(firstPromise === secondPromise);
   });
});
 
describe("when refresh is called twice yet some time apart", function() {
   before(function() {
      widget = new LogViewer();
   });
 
   it("should procure two separate promises", function() {
      var firstPromise = widget.refresh();
      firstPromise.then(function(){
         var secondPromise = widget.refresh();
         assert.isFalse(firstPromise === secondPromise);
      });
   });
});

 
 

The widget is a dojo widget shaped in part like so to ensure that it will not spin up a promise at the refresh function if one is already in play:

postCreate: function() {
   this.refreshPromise = null;
},
 
refresh: function() {
   if(!this.refreshPromise) {
      
some stuff here...
      this.refreshPromise = whatever.doAct(options).then(lang.hitch(this, function(items) {
         
guts of the magic...
         this.refreshPromise = null;
      }),
         function(error) {
            this.refreshPromise = null;
      });
   }
   return this.refreshPromise;
}

No comments:

Post a Comment