My backend retrieves me a 'x-token' when a user log in successfully on my web. On my frontend I do a simple validation, getting this token and setting: $rootScope.authenticated = true; if the token is not present on the header response for any reason my frontend sets: $rootScope.authenticated = false;
My Controller
signinService
.signin(datafromForm)
.then(function (data) {
if ( $myTokenManager.save(data.headers('x-token')) ) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
// Unit test is sent it here :(
}
});
This is working perfect, now I need to do a unit test for this method, but my test is not generating or setting the header response properly. What am I doing wrong on my test?
describe('Testing controllers', function() {
describe('MyController unit test', function() {
var $httpBackend, $rootScope, createController, authRequestHandler, datafromForm;
beforeEach(module('myapp'));
beforeEach(inject(function($injector) {
$httpBackend = $injector.get('$httpBackend');
authRequestHandler = $httpBackend
.when(
'POST',
'http://mywebapp:8080/loginuser',
{"username":"admin", "password":"admin"}
).respond({'x-token': 'XXX'});
$rootScope = $injector.get('$rootScope');
var $controller = $injector.get('$controller');
createController = function() {
return $controller('MyController', {'$scope' : $rootScope});
}
}));
//
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
//
it('should authentication user', function() {
var controller = createController();
//
$rootScope.username = "admin";
$rootScope.password = "admin";
datafromForm = {
username: $rootScope.username,
password: $rootScope.password
};
$httpBackend.expectPOST(
'http://mywebapp:8080/loginuser',
{"username":"admin", "password":"admin"}
).respond(
200,
{'x-token': 'XXX'}
);
$rootScope.login(formData);
$httpBackend.flush();
expect($rootScope.authenticated).toBe(true); // This is getting false :(
});
});
});
I'm following this example on angular documentation.