FirebaseExtended / angularfire

AngularJS bindings for Firebase
MIT License
2.73k stars 632 forks source link

Testing components that use angularFire #307

Closed jackfranklin closed 10 years ago

jackfranklin commented 10 years ago

Hello,

I was just wondering if anyone had any advice on how to go about unit testing components that use AngularFire, in particular mocking the $firebase object so it doesn't hit the network.

As an example, take this service I have that grabs my todos from a Firebase:

module.exports = function(app) {
  app.factory('TodoService', function($firebase, FIREBASE_URL) {
    var todosRef = new Firebase(`${FIREBASE_URL}/todos`);
    var fbRef = $firebase(todosRef);
    fbRef.markTodoAsDone = function(todoId) {
      fbRef.$child(todoId).$update({ done: true });
    };

    fbRef.markTodoAsStarted = function(todoId) {
      fbRef.$child(todoId).$update({ state: 'STARTED' });
    };

    fbRef.addRefToTodo = function(todoId, ref) {
      var todo = fbRef.$child(todoId);
      todo.$on('loaded', () => {
        var refs = todo.references || [];
        refs.push(ref);
        todo.$update({ references: refs });
      });
    };

    fbRef.addTagToTodo = function(todoId, tag) {
      var todo = fbRef.$child(todoId);
      todo.$on('loaded', () => {
        var tags = todo.tags || [];
        tags.push(tag);
        todo.$update({ tags: tags });
      });
    };
    return fbRef;
  });
};

In tests, I'd like to mock $firebase to give back an object that has some (fake, static) todos (fixtures, if you will). Does anyone have any advice on how? I'm not sure of the best way to go about it.

I'd also need the fake $firebase to be pretty clever - mocking the $child method, and $on('loaded', fn) too so I could test addTagToTodo and similar.

Cheers,

Jack

bendrucker commented 10 years ago

Have you tried the mock Firebase library used in the tests?

https://github.com/firebase/angularFire/blob/master/tests/lib/MockFirebase.js

katowulf commented 10 years ago

The latest version of MockFirebase is here; much improved over the version in the current angularFire master branch: https://github.com/katowulf/mockfirebase