Catfish
Catfish

Reputation: 19294

Angular unit test that calls a service

I have a very simple controller that has a scope variable that calls a service method to get populated. I'm trying to write the test make sure this variable gets populated, but i'm getting the error Expected spy find to have been called.

How can I write this unit test using spy for the service piece?

describe('StuffCtrl', function() {

    beforeEach(module('web'));

    var scope, ctrl, stuff;

    beforeEach(inject(function($rootScope, $controller, Stuff) {
      scope = $rootScope.$new();
      stuff = Stuff;
      ctrl = $controller('StuffCtrl', {$scope: scope, Stuff: stuff});
    }));

it('should fetch all the stuff', function() {

    // Mock the Stuff.find service
    spyOn(stuff, 'find');

    // ERROR ON THIS LINE: Expected spy find to have been called.
    expect(stuff.find).toHaveBeenCalled();
    expect(scope.stuff).toBeDefined();
  });
...

Controller

angular.module('web').controller('StuffCtrl',function($scope, $log, $routeParams, $location, Stuff){

  $scope.stuff = Stuff.find();

});

Stuff service

module.factory("Stuff", ['LoopBackResource', '$injector', function(Resource, $injector) {

  var R = Resource(
      urlBase + "/stuff/:id",
      { 'id': '@id' },
      {"find": {
          url: urlBase + "/stuffs",
          method: "GET",
          isArray: true,
        }
      });


    return R;
  }]);

Upvotes: 1

Views: 223

Answers (1)

mpm
mpm

Reputation: 20155

try this

describe('StuffCtrl', function() {

    beforeEach(module('web'));

    var scope, ctrl, stuff;

    beforeEach(inject(function($rootScope, $controller, Stuff) {
      scope = $rootScope.$new();
      stuff = Stuff;
      // Mock the Stuff.find service
      spyOn(stuff, 'find');
      //you're instanciating the controller here so find will get executed.
      //you need to mock find before.
      ctrl = $controller('StuffCtrl', {$scope: scope});
    }));

it('should fetch all the stuff', function() {
    expect(stuff.find).toHaveBeenCalled();
    expect(scope.stuff).toBeDefined();
  });
...

Upvotes: 2

Related Questions