jeudi 19 novembre 2015

Using Jasmine to mock nested ES6 promises

I am trying to use Jasmine to mock a series of nested promises and return fakes. An simple example of my code is:

export default {
  getUserAvatar() {
    this.getUser().then(user => {
      this.getAvatar(user.id).then(avatar =>
        return avatar;            
      });
    });
  },

  getUser() {
    return UserService.getUser();
  },

  getAvatar(userId) {
    return AvatarService.getAvatar(userId)
  }
}

and a snippet of the tests:

  spyOn(Tournaments, 'getUser').and.callFake(function() {
    let p = new Promise(resolve => {
      let userModel = new Backbone.Model({ memberId: userId });
      resolve(userModel);
    });
    return p;
  });

  spyOn(Tournaments, 'getAvatar').and.callFake(function() {
    let p = new Promise(resolve => {
      let res = {
        data: '{"avatar": "id:2"}'
      };
      resolve(res);
    });
    return p;
  });

I am using ES6 modules and the code is in a 'Tournaments' module. The problem I am having is that only the first fake function gets called. In the above example the original getAvatar function gets called and not the fake. Can anyone explain this or guide me to better solution?

Aucun commentaire:

Enregistrer un commentaire