jefflage
jefflage

Reputation: 31

How to test logic in joined promises/then

I am trying to write a test for an action handler on one of my components. I am stubbing out the save method on one of my models to return a resolved promise using Em.RSVP.Promise.resolve()

in my component, i chain on that promise using then:

return target .save() .then(function(){ selected.rollback(); this.sendAction('quicklinkChanged', target); }.bind(this),this.notify_user_of_persistence_error.bind(this, 'Save As'));

this is a pattern that i use a lot server-side where we use when for our promise library. however, when i do this client-side, i never end up inside the function in the then block so i cannot assert any of the functionality there in my unit tests.

can anyone provide any insight on the best way to do this?

Upvotes: 1

Views: 52

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

We moved our callbacks out of the method so we could call them separately and verify functionality, or replace them and verify they were called.

Controller Example:

App.IndexController = Em.Controller.extend({
  randomProperty: 1,
  async: function(fail){
    return new Em.RSVP.Promise(function(resolve, reject){
      if(fail){
        reject('fdas');
      }else{
        resolve('foo');  
      }
    });
  },
  doAsyncThing: function(fail){
    return this.async(fail).then(this.success.bind(this), this.failure.bind(this));
  },
  success: function(){
    this.set('randomProperty', 2);
  },
  failure: function(){
    this.set('randomProperty', -2);
  }
});

Tests

test("async success", function(){
  var ic = App.IndexController.createWithMixins();
  stop();
  ic.doAsyncThing(false).then(function(){
    start();
    equal(ic.get('randomProperty'), 2);
  });

});

test("async fail", function(){
  var ic = App.IndexController.createWithMixins();
  stop();
  ic.doAsyncThing(true).then(function(){
    start();
    equal(ic.get('randomProperty'), -2);
  });

});

test("async success is called", function(){
  expect(1);
  var ic = App.IndexController.createWithMixins();
  ic.success = function(){
    ok(true);
  };
  stop();
  ic.doAsyncThing(false).then(function(){
    start();
  });

});

test("async failure is called", function(){
  expect(1);
  var ic = App.IndexController.createWithMixins();
  ic.failure = function(){
    ok(true);
  };
  stop();
  ic.doAsyncThing(true).then(function(){
    start();
  });

});

test("doAsyncThing returns a promise", function(){
  expect(1);
  var ic = App.IndexController.createWithMixins();
  ok(ic.doAsyncThing(true).then);

});

Example: http://emberjs.jsbin.com/wipo/37/edit

Upvotes: 2

Related Questions