Your User.login
function must be calling the callback method asynchronously, so when you call scope.submit();
, your callback function is not called yet => the test fails.
To test this logic, you have to mock the User.login
function:
it('should redirect upon successful login', function() {
console.log('before path = '+location.path());
scope.user = {
"username": "my_user",
"password": "my_pass"
};
//user here is user = User; in your beforeEach. I avoid pasting too much code.
//Jasmine 1.3: andCallFake
//Jasmine 2.0: and.callFake
spyOn(user, "login").andCallFake(function(userData,successCallback){
successCallback(userData); //simulate the success case.
}); //mock your User.login
scope.submit();
console.log('message = '+scope.message);
console.log('after path = '+location.path());
console.log(window.sessionStorage.getItem('token'));
expect(location.path()).toEqual('/dashboard'); //fix the problem with location.path
});
Explanation:
spyOn(user, "login").andCallFake
replaces the actual function with our fake function.
In this test case, you're testing should redirect upon successful login
, so the precondition is the login must be successful, by mocking the login function, we can ensure this precondition is always true in the test.
You could do this similarly to test a case like: set error message when login failed
, in order to test this, you need to ensure the precondition login failed
is always true in the test:
it('should redirect upon successful login', function() {
console.log('before path = '+location.path());
scope.user = {
"username": "my_user",
"password": "my_pass"
};
//user here is user = User; in your beforeEach. I avoid pasting too much code.
//Jasmine 1.3: andCallFake
//Jasmine 2.0: and.callFake
spyOn(user, "login").andCallFake(function(userData,successCallback,errorCallback){
errorCallback(userData); //simulate the error case.
}); //mock your User.login
scope.submit();
expect(scope.message).toEqual('Error: Invalid user or password'); //verify that the message was set correctly.
});