So, I'm new to the world of JavaScript and AngularJS, and so my code is not as good as it should be, but it is improving. However, I began to learn and implement a simple login page using REST Backend. After submitting the login form, the authentication token is returned and set as the default http header property, similar to this
$http.defaults.headers.common['X-AUTH-TOKEN'] = data.authToken;
This works fine when I check it manually, but it isnβt, so I would like to implement unit-test, which checks if the X-AUTH-TOKEN header is set.
Is there any way to check this with $ httpBackend? For example, I have the following test:
describe('LoginController', function () { var scope, ctrl, $httpBackend; // Load our app module definition before each test. beforeEach(module('myApp')); // The injector ignores leading and trailing underscores here (ie _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function (_$httpBackend_, $rootScope, $controller) { $httpBackend = _$httpBackend_; scope = $rootScope.$new(); ctrl = $controller('LoginController', {$scope: scope}, {$http: $httpBackend}, {$location: null}); })); it('should create an authToken and set it', function () { $httpBackend.expectPOST('http://localhost:9000/login', '200').respond(200, '{"authToken":"52d29fd63004c92b972f6b99;65e922bc-5e33-4bdb-9d52-46fc352189fe"}'); scope.login('200'); $httpBackend.flush(); expect(scope.data.authToken).toBe('52d29fd63004c92b972f6b99;65e922bc-5e33-4bdb-9d52-46fc352189fe'); expect(scope.loginValidationOverallError).toBe(false); expect(scope.status).toBe(200); });
My controller is as follows:
.controller('LoginController', ['$scope', '$http', '$location', function ($scope, $http, $location) { // Login Stuff $scope.data = {}; $scope.status = {}; $scope.loginValidationOverallError = false; $scope.login = function (user) { $http.post('http://localhost:9000/login', user).success(function (data, status) { $scope.data = data; $scope.status = status; $scope.loginValidationOverallError = false; console.log($scope.status, $scope.data); $http.defaults.headers.common['X-AUTH-TOKEN'] = data.authToken; $location.path('/user'); }).error(function (data, status) { console.log(status + ' error'); $scope.loginValidationOverallError = true; }); }; ...
I checked the documentation at http://docs.angularjs.org/api/ngMock.$httpBackend , but not sure if the last test really applies to my code (and how this code really checks something)
it('should send auth header', function() { var controller = createController(); $httpBackend.flush(); $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {