Currently, I am developing an application using AngularJs 1.4.4 and have recently started implementing Test-Driven Development (TDD) for the first time. I am utilizing Karma with Jasmine for testing and have encountered a challenge while trying to test an expression defined using 'this' in a Controller - it returns as undefined. Although Angular recommends using 'this' in controllers as best practice, I have struggled to find clear examples of how to effectively test it.
Below is the code snippet of my Controller:
'use strict';
var app = angular.module('app', ['ngRoute', 'ngAnimate']);
angular.module('app')
app.controller('LoginCtrl', ['$scope', function($scope) {
var login = this;
login.user = {message:'hello'};
$scope.userName = "Anthony";
}])
And here is my test script:
'use strict';
describe('Controller: LoginCtrl', function() {
// load the controller's module
beforeEach(module('app'));
var LoginCtrl,
scope;
// initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
LoginCtrl = $controller('LoginCtrl', {
$scope: scope,
});
}));
it('should equal to Anthony', function() {
expect(scope.userName).toBe("Anthony");
});
it('login user should equal to hello', function() {
expect(login.user.message).toBe('hello');
})
});
Although the first test passes successfully, the second one results in an error/failure message:
Controller: LoginCtrl login user should equal to hello FAILED
TypeError: 'undefined' is not an object (evaluating 'login.user.message')
I presume that it requires injection similar to the controller and scope, but my attempts so far have been unsuccessful. Any assistance would be greatly appreciated :)