When I create a new controller, it automatically triggers a method linked to the $scope
:
angular.module('example', []).controller('exampleCtrl', function($scope) {
$scope.method = function () { ... };
$scope.method();
});
I am trying to verify that this method is indeed called during the controller's creation. To do this, I am using jasmine for testing and sinon.js for mocking.
describe('tests', function() {
var $scope, $controller;
beforeEach(inject(function($rootScope, _$controller_) {
$scope = $rootScope.$new();
$controller = _$controller_;
});
describe('During construction', function() {
it('should call "method"', function() {
$controller('exampleCtrl', { $scope: $scope });
var methodStub = sinon.stub($scope, 'method');
expect(methodStub.called).toBe(true);
});
});
});
However, my test fails because the $scope.method()
is invoked immediately after $controller()
, which doesn't give me time to stub it out. I tried to stub it out before creating the controller:
it('should call "method"', function() {
var methodStub = sinon.stub($scope, 'method');
$controller('exampleCtrl', { $scope: $scope });
expect(methodStub.called).toBe(true);
});
But then I encountered an error from sinon:
TypeError: Cannot read property 'restore' of undefined
. This happened because $scope.method
was not yet defined since the constructor had not been called.
I also experimented with directly stubbing the method on the $scope
, like this $scope.method = sinon.stub()
, but unfortunately, it gets overridden during the controller's construction.
Is there a way to successfully stub a method called during the controller's construction?