jeudi 28 mai 2015

AngularJS testing with firebase/mockfirebase in a service

I've been trying to write some unit tests for my services which use AngularFire to communicate with Firebase inside an Angular website.

I'm new to AngularJS and so I feel like I'm missing something obvious but couldn't find any great examples online (at least not that spoke to my limited knowledge).

I found some limited docs on MockFirebase http://ift.tt/1JasApg and that showed how to pretty much mock out the data so I did that.

For further examples of mockfirebase I looked at the angular fire's unit tests http://ift.tt/1EC3Csr but that didn't seem to show me the right way.

Here is my service --

app.service('Subscription', function ($firebase, FIREBASE_URL, $q) {

var ref;
var Subcription = {
ref: function () {
  if (!ref) ref = new Firebase(FIREBASE_URL + "/subscriptions");
  return ref;
},

validateSubscription: function(userId){
  var defer = $q.defer();

  $firebase(Subcription.ref().child(userId))
    .$asObject()
    .$loaded()
    .then(function (subscription) {
      defer.resolve(subscription.valid === true);
    });

  return defer.promise;
},

recordSubscription: function(userId){
  return Subcription.ref().$set(userId, {valid: true});
}

};

 return Subcription;

});

Here is the spec file --

describe('Service: subscription', function () {

  // load the service's module
  beforeEach(module('clientApp'));

  // instantiate service
  var subscription;
  var scope;
  beforeEach(inject(function (_Subscription_, $rootScope) {
    MockFirebase.override();
    subscription = _Subscription_;
    scope = $rootScope.$new();
  }));

  it('allows access when the user id is in the subscription list', function () {
    subscription.ref().push({'fakeUser': {access: true}});
    subscription.ref().flush();

    var handler = jasmine.createSpy('success');
    subscription.validateSubscription('fakeUser').then(handler);

    scope.$digest();
    expect(handler).toHaveBeenCalledWith(true);
  });

});

It seems like the problem is that the promise never gets resolved inside of $asobject.$loaded because that angularfire part isn't happening.

I get the following as a result of the test: 'Expected spy success to have been called with [ true ] but it was never called.'

Aucun commentaire:

Enregistrer un commentaire