angular.module('MyApp')
.controller('loginCtrl', function($scope, $rootScope, $location, $window, $auth) {
$scope.login = function() {
$auth.login($scope.user)
.then(function(response) {
if(response.data.users.status === 'success'){
$rootScope.currentUser = response.data.username;
$window.localStorage.user = JSON.stringify(response.data.users);
$location.path('/');
}
}).catch(function(response){
if(response.data.users.status === 'error'){
$scope.error = response.data.users.error;
}
})
};
});
I get the error:
users is undefined error
when testing above code with Karma and Jasmine.
The spec is below:
describe('LogController', function() {
var $scope, controller, $location, $window;
beforeEach(module('MyApp'));
beforeEach(inject(function($rootScope, $controller, _$location_ , _$window_ , _$httpBackend_) {
$scope = $rootScope.$new();
$window = _$window_
$httpBackend = _$httpBackend_;
$location = _$location_;
controller = $controller('loginCtrl', {
$scope: $scope,
$location: $location,
$window: $window
});
}))
it('should log in a user and redirect to homepage', function() {
$httpBackend.when('POST','/user/auth').respond(200);
//whitelist all view
$httpBackend.whenGET(/partials.*/).respond(200, '');
$scope.username = 'test';
$scope.password = '123456';
$scope.login();
$httpBackend.flush();
$scope.$apply();
expect($location.path()).toBe('/x');
});
})
What is users undefined? And how do I mock out a response from $window.localStorage so it won't be?
Youshould mock the response for login
$httpBackend.when('POST','/user/auth').respond(200, mockResponseData);
where:
mockResponseData = {
"data": {
"username": "someValue",
"users": {
"status": "success"
}
}
}
Related
I have my pseudonym in the $scope and I try to access it from other views after the user has logged in, using:
however, when I refresh the page immediately after the user has successfully signed in, the $scope value reverts back into {{pseudonym}} and the parameter isn't available. How can I save this data persistently throughout the logged in session? Can you please provide the answer with an example?
app.controller("MyregisterCtrl", ["$scope", "$stateParams", "Auth", "$state", "$location", "$modal", "DatabaseRef", "$rootScope",
function ($scope, $stateParams, Auth, $state, $location, $modal, DatabaseRef, $rootScope) {
$scope.user = {};
$scope.signIn = function () {
if (!$scope.user.email && !$scope.user.password) {
toastr.error("Add email and password");
} else {
Auth.$signInWithEmailAndPassword($scope.user.email, $scope.user.password)
.then(function(firebaseUser) {
var userId = firebase.auth().currentUser.uid;
DatabaseRef.ref('/users/' + userId).once('value')
.then(function(snapshot) {
pseudonym = snapshot.val().pseudonym;
console.log("pseudonym: ", pseudonym);
$scope.pseudonym = pseudonym;
});
$state.go('app.dashboard');
if (!firebaseUser.emailVerified) {
// firebaseUser.sendEmailVerification();
toastr.info('Your email is NOT verified.', 'Verify email!');
$state.go('login.signin');
}
// $state.go('home');
})
.catch(function(error) {
toastr.error(error.message, error.reason, { timeOut: 10000 });
$scope.user = {};
})
}
};
You should use a Service to store the value and retrieve it whenever you need.
var myApp = angular.module('myApp',[]);
myApp.service('mySingleton', function() {
var username= "test";
return {
username : username
};
});
function MyCtrl($scope, mySingleton) {
$scope.username= mySingleton.username;
}
function MyCtrl2($scope, mySingleton) {
$scope.username= mySingleton.username;
}
How do I include ui.bootstrap. I use ui.bootstrap to open the bootstrap modal(open) on ng-click. After that I want to send all modal data to server, for that I use $http in my angular controller. But it gives an error. Below is my angular js code.
var app = angular.module("modalFormApp", ['ui.bootstrap']);
app.controller("modalAccountFormController", ['$scope', '$modal', '$log', '$http'
function($scope, $modal, $log, $http) {
$scope.showForm = function() {
$scope.message = "Show Form Button Clicked";
console.log($scope.message);
var modalInstance = $modal.open({
templateUrl: 'modal-form.html',
controller: ModalInstanceCtrl,
scope: $scope,
resolve: {
userForm: function() {
return $scope.userForm;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.selected = selectedItem;
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
};
}
]);
app.controller('ModalInstanceCtrl', ['$scope', '$http', '$modalInstance', userForm, function($scope, $http, $modalInstance, userForm) {
//var ModalInstanceCtrl = function ($scope, $modalInstance,$http, userForm) {
$scope.form = {}
$scope.url = 'submit.php';
$scope.submitForm = function() {
if ($scope.form.userForm.$valid) {
$http.post($scope.url, {
"name": $scope.name,
"email":
$scope.email,
"message": $scope.message
}).
success(function(data, status) {
console.log(data);
$scope.status = status;
$scope.data = data;
$scope.result = data;
})
} else {
console.log('userform is not in scope');
}
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
}])
'ui.bootstrap' has prerequisites 'ngAnimate' and 'ngTouch'. You should add them to your module
var app = angular.module("modalFormApp", ['ngAnimate','ngTouch','ui.bootstrap']);
And you should add their scripts to your view
script(src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-animate.min.js")
script(src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-touch.min.js")
I need help, been searching and thinking for hours but didn't come up with a good solution. I am experiencing error "Expected undefined to be defined" which is repeatedly occurs when I call $scope in my It() functions.
Spec.js
describe("C0001Controller", function(){
var $scope,
$rootScope,
$injector,
$controller,
$httpBackend,
$loading,
C0001Controller;
describe("initialize controllers",function(){
beforeEach(function(){
angular.module('app.c0001App');
})
beforeEach(inject(function(_$rootScope_, _$injector_, _$controller_, _$httpBackend_, _$loading_)
{
$rootScope = _$rootScope_;
$injector = _$injector_;
$controller = _$controller_;
$httpBackend = _$httpBackend_;
$loading = _$loading_;
$scope = $rootScope;
C0001Controller = $controller('C0001Controller', {
$scope: $scope,
$loading : $loading
});
}));
});
it("should use the user ",function(){
var languages = [{id: "en", name: "English"}, {id: "jp", name: "Japanese"}];
expect(languages).toBeDefined();
it("should read if there are languages used", function(){
expect($scope).toBeDefined();
});
describe("checking connection to module and controller", function(){
it("should be connected to module", function(){
expect("app.c0001App.C0001Controller").toBeDefined();
});
it("contains C0001Spec Spec", function(){
expect(true).toBe(true);
});
it("should be equal to user", function(){
var user = {};
var c0001Data = user;
expect(c0001Data).toBe(user);
});
});
});
I was thinking if the format I did in the karma.conf.js file has a mistake.
// list of files / patterns to load in the browser
files: [
'node_modules/angular/angular.js',
'node_modules/angular-mocks/angular-mocks.js',
'app/*.js',
'tests/*.js'
],
here's my Controller.js
angular.module('app.c0001App', [
'ui.router'
])
.config(function($stateProvider) {
$stateProvider.state('/c0001', {
url : '/c0001'
, templateUrl : 'pages/C0001.html'
, data : {
pageTitle: 'LOGIN'
}
});
})
.controller('C0001Controller', function ($rootScope, $scope, $http, $window, $location, $loading) {
var promise = $http.get('changeLanguage.do?lang=en');
promise.success(function(data, status, headers, config) {
//some codes here
Thank you in advance.
I'm having trouble understanding how the scope gets initialized in karma tests. i'm expecting a scope variable to be preset when the test runs, but it keeps coming back as undefined.
What am I missing?
Test Case
describe('loginController', function() {
beforeEach(module('app'));
var $controller, $scope;
beforeEach(inject(function(_$controller_, $rootScope){
$controller = _$controller_;
$scope = $rootScope.$new();
}));
describe('$scope.login', function() {
beforeEach(function() {
controller = $controller('loginController', { $scope: $scope });
});
it('checks it initialized', function() {
expect($scope.foo).toEqual('foo');
expect($scope.bar).toEqual('bar');
//expect($scope).toBeDefined();
//expect($scope.loginData.userName).toEqual('');
//expect($scope.loginData.password).toEqual('');
});
The controller:
angular.module('app').controller('loginController', ['$location',
'authService', function($scope, $location, authService) {
$scope.foo = 'foo';
$scope.bar = 'bar';
$scope.loginData = {
userName: '',
password: ''
};
}]);
I refactored the test code and now it works:
describe('loginController', function() {
beforeEach(module('app'));
var controller, scope;
beforeEach(inject(function($controller, $rootScope){
scope = $rootScope.$new();
console.log('scope1', scope);
controller = $controller('loginController', {
$scope: scope
});
}));
describe('login', function() {
it('sets variables ', function() {
expect(scope).toBeDefined();
expect(scope.loginData).toBeDefined();
expect(scope.loginData.userName).toEqual('');
expect(scope.loginData.password).toEqual('');
});
});
});
try injecting $controller to the function where you instantiate the controller:
beforeEach(inject(function($controller) {
controller = $controller('loginController', { $scope: $scope });
}));
I've a unit tests that's keep failing with the error above not sure what exactly is wrong with this, by the looks of the error, its says that I need to declare a function. Can someone point me what is wrong with my code please:
unit test
describe('Test loginService', function() {
var $location, loginService, $scope, authentication, $rootScope;
beforeEach(function() {
module('app');
inject(function(_$location_, _$rootScope_, _loginService_,
_authentication_) {
$location = _$location_;
authentication = _authentication_;
loginService = _loginService_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
});
});
it('Should successfully login with correct credentials', function() {
$scope.username = 'a#a.com';
$scope.password = 'a';
spyOn($location, 'url');
loginService.login($scope);//Complains about this line
expect($location.url).toHaveBeenCalled();
expect($location.url).toHaveBeenCalledWith('/home');
});
login service
app.factory('loginService', function(parserService, $location,
authentication, $rootScope) {
return {
login : function(scope) {
parserService.getData().then(function(data) { //This line
if (scope.username === data.username
&& scope.password === data.password) {
...
$location.url("/home");
} else {
scope.loginError = "Invalid Credentials";
}
});
}
});
Json file reader service
app.factory('parserService', function($http, $q) {
return {
getData: function() {
var deferred = $q.defer();
$http.get('res/file.json').success(function(data) {
deferred.resolve(data);
}).error(function(){
deferred.reject();
});
return deferred.promise;
}
}
});
error log
Chrome 36.0.1985 (Windows 7) Test loginService Should successfully login with correct credentials FAILED
TypeError: undefined is not a function
at Object.login (D:../js/services/loginService.js:6:18)
at null.<anonymous> (D:/../test/unit/loginTest.js:92:16)
since you can't format a comment, I'm using an answer... :D
have you tried this?
var $location, loginService, $scope, authentication, $rootScope, parserService;
beforeEach(function() {
module('app');
inject(function(_$location_,
_$rootScope_,
_parserService_,
_loginService_,
_authentication_) {
$location = _$location_;
authentication = _authentication_;
loginService = _loginService_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
parserService = _parserService_;
});
});