jeudi 25 décembre 2014

Getting “Unexpected request” error when running Karma unit test in an AngularJS app

I have seen some questions regarding this but all of them was specific to each case and I couldn't find a solution for my case in those posts.


I have a current controller:



function Login(authService, $scope) {

var vm = this;

vm.submit = submit;

vm.form = {};

function submit() {
if ($scope.loginForm.$invalid) {
vm.invalid = true;
return;
} else {
var data = {
usr: vm.form.email,
pwd: vm.form.password,
vendorId: 99
};
authService.login(data).then(success, error);
}
}

function success(res) {
if (res.data) {
//Do stuff
}
}

function error(error) {
console.log("Error ", error);
}

}


And the following unit test:



describe('Login', function() {
beforeEach(module('app'));

var loginCtrl, scope, $httpBackend, authService;
var loginResponse = [{
"data": {
"avatar": "avatar",
"gender": "M",
"hid": "hid,
"id": "id",
"role": "Adult",
"token": "token"
}
}];
var loginRequest = { "usr": "test@teste.com", "pwd": "123teste!", "vendorId": 99 };

beforeEach(inject(function($rootScope, _$httpBackend_, $controller, _authService_) {
$httpBackend = _$httpBackend_;
scope = $rootScope.$new();
loginCtrl = $controller('Login', {
$scope: scope
});
authService = _authService_;

}));

afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});

describe("submit", function() {
it("should send login data to the server", function() {
// expect(loginCtrl.login).toBe(false);

//Tells the $httpBackend service to expect a POST call to be made to a service and that it will return
//loginResponse object that was defined before
$httpBackend.expectPOST('api/current/api/login').respond(loginResponse);

//Execution of the service
var deferred = authService.login(loginRequest);
var users;
deferred.then(function(response){
users = response.data;
});
// expect(loginCtrl.login).toBe(true);

//Preserve the asynchronous nature of the call while at the same time be able to test the response of the call
$httpBackend.flush();

// dump(users);
expect(users).toEqual(loginResponse);
// expect(loginCtrl.login).toBe(true);
});

});



});


And I am getting the error:



Error: Unexpected request: GET signup/signup.html
No more request expected


I have found why this error occurs (I think). I'm using ui-router and it seems that it is always trying to do a GET request for the router root:



$urlRouterProvider.otherwise('/signup/');

$stateProvider
/* NOT AUTHENTICATED STATES */
.state('signup', {
url: '/signup/',
templateUrl: 'signup/signup.html',
controller: 'Signup as signupCtrl',
data: {
authorizedRoles: [AUTH_EVENTS.notAuthenticated]
}
})


Now I have no idea why, or how to fix it... Can someone understand what I'm doing wrong?


Thanks in advance!


Aucun commentaire:

Enregistrer un commentaire