So I am writing unit tests for an application in angularJS using Jasmine.
I have a controller with an "init" method which calls "secondMethod" and "thirdMethod"
I want to test with a jasmine spyOn whether "secondMethod" is called correctly.
My controller looks like this:
function init() {
secondMethod().then(function () {
thirdMethod();
});
}
init();
function secondMethod(){
//do something
}
function thirdMethod(){
//do something
}
and my test file looks like this:
describe("nameOfTheController", function () {
var $rootScope,
$controller,
$scope,
controller;
beforeEach(function () {
angular.mock.module("myModule");
inject(function (_$controller_, _$rootScope_) {
$rootScope = _$rootScope_;
$controller = _$controller_;
$scope = $rootScope.$new();
controller = $controller('nameOfTheController', {
'$scope': $scope
});
});
});
describe("init", function(){
it('should run secondMethod', function(){
spyOn(controller, 'secondMethod');
expect(controller.secondMethod).toHaveBeenCalled();
});
it('should run thirdMethod', function(){
spyOn(controller, 'thirdMethod');
expect(controller.thirdMethod).toHaveBeenCalled();
});
As you can see I inject the controller in beforeEach but I get error that method "secondMethod" and "thirdMethod" are not defined and I am not quite sure why.
I have also tried doing something like the following but to no avail
controller:
var vm = this;
vm.init = function() {
vm.secondMethod().then(function () {
vm.thirdMethod();
});
}
vm.init();
vm.secondMethod = function(){
//do something
}
vm.thirdMethod = function(){
//do something
}
testfile:
describe("nameOfTheController", function () {
var $rootScope,
$controller,
$scope,
controller;
beforeEach(function () {
angular.mock.module("myModule");
inject(function (_$controller_, _$rootScope_) {
$rootScope = _$rootScope_;
$controller = _$controller_;
$scope = $rootScope.$new();
controller = $controller('nameOfTheController', {
'$scope': $scope
});
});
});
describe("init", function(){
it('should run secondMethod', function(){
spyOn(controller, 'secondMethod');
expect(controller.secondMethod).toHaveBeenCalled();
});
it('should run thirdMethod', function(){
spyOn(controller, 'thirdMethod');
expect(controller.thirdMethod).toHaveBeenCalled();
});
Does anyone know why second and third method are undefined?
EDIT:
The reason why second and third method returned undefined when prefixing with "vm." was that the init function was called before the second and third method had been defined.
Moving the call of init to be below the second and third method definitions solved the problem. Now I just have the problem that the spy expects the method to be called but it doesn't get called
var vm = this;
vm.init = function() {
vm.secondMethod().then(function () {
vm.thirdMethod();
});
}
vm.secondMethod = function(){
//do something
}
vm.thirdMethod = function(){
//do something
}
vm.init();
Aucun commentaire:
Enregistrer un commentaire