Search code examples
javascriptangularjsunit-testingkarma-jasminekarma-mocha

Cannot read property 'spyOn' of null - Mocking a promise in angularJS unit test


I am trying to mock a function which returns a promise using spyOn with the following code:

  beforeEach(inject(function($controller, $rootScope, $q) {
    scope = $rootScope.$new();
    q = $q;

    ctrl = $controller('BillingCtrl', {
      $scope: scope,
      $q: q
    });
  }));

  it('should have overlay off when cancel modal is shown', 
    function() {

      var deferred = q.defer();
      deferred.resolve();

      spyOn(scope, 'confirmModal').andReturn(deferred.promise); 

      scope.cancelSubscription(""); //scope.confirmModal is called within here.
      expect(scope.overlayOn).to.equal(true);
  });

This throws this error:

Chrome 37.0.2062 (Mac OS X 10.9.2) Unit: BillingController "before each" hook: workFn FAILED
    TypeError: Cannot read property 'spyOn' of null

scope.confirmModal definitely exists in this context as I'm able to console.log it.

Any pointers would be appreciated!


Solution

  • I figured it out.

    Mocha was conflicting with Jasmine (I was using them both).

    The spyOn function works fine when I remove Mocha.