trying to do a resolve with a promise - javascript

I am trying to do a resolve with a promise due to an issue with a filters I am working on, but, my resolve isn't working yet.
I am doing this because in a question I did before some one asked me to do a resolve which is the must logic solution I got from other people.
This what the console returns:
localhost:1337/lines/sports/undefined:1
GET http://localhost:1337/lines/sports/undefined 400 (Bad Request)
Take a look at my code:
app.js
.state('app.sports', {
url:'/sports',
views:{
menuContent:{
templateUrl:'templates/sportsList.html',
controller:'SportsController',
resolve: {
Sports: function(SportsFactory, AuthFactory, $q) {
var defer = $q.defer();
console.log(AuthFactory);
AuthFactory.getCustomer().then(function() {
SportsFactory.getSports().then(function(sports) {
defer.resolve(sports);
});
});
return defer.promise;
}
}
controller.js
.controller('SportsController', function($scope, $state,
AuthFactory, SportsFactory, Sports) {
$scope.query = '';
$scope.sports = Sports;
$scope.sports = [];
$scope.customer = {};
});
AuthFactory.getCustomer().then(function(customer) {
$scope.customer = customer;
SportsFactory.getSportsWithLeagues(customer).then(function(sports) {
if (sports.length) {
$scope.sports = sports;
}else {
AuthFactory.logout();
}
}, function(err) {
console.log(err);
});
}, function(err) {
console.log(err);
});
service.js
.factory('SportsFactory', function($http, $q, AuthFactory,
LocalForageFactory, LeaguesFactory, CONSTANT_VARS) {
return {
getSports: function(agent) {
var defer = $q.defer();
LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_SPORTS)
.then(function(sports) {
if (!_.isNull(sports)) {
defer.resolve(_.values(sports));
}else {
$http.get(CONSTANT_VARS.BACKEND_URL + '/lines/sports/' + agent)
.success(function(sports) {
//forcing array instead of object
sports = _.values(sports);
sports = _.sortBy(sports, function(sport) {
return sport.priority;
});
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_SPORTS, sports);
defer.resolve(sports);
})
.error(function(err) {
defer.reject(err);
});
}
});
return defer.promise;
},
getSportsWithLeagues: function(customer) {
var _this = this,
defer = $q.defer(),
rejection = function(err) {
defer.reject(err);
},
sportsLength;
LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES)
.then(function(sportLeagues) {
if (!_.isNull(sportLeagues)) {
//forcing array instead of object
sportLeagues = _.values(sportLeagues);
defer.resolve(sportLeagues);
}else {
_this.getSports(customer.agent).then(function(sports) {
sportsLength = sports.length;
LeaguesFactory.getLeagues({
sportIds: _.pluck(sports, 'id'),
lineProfile: customer.lineProfile,
betLimit: customer.betLimit
}).then(function(leagues) {
_.each(sports, function(sport) {
sport.leagues = _.filter(leagues, function(league) {
return sport.id === league.sport.id;
});
});
//forcing array instead of object
sports = _.values(sports);
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES, sports);
defer.resolve(sports);
}, rejection);
}, rejection);
}
}, rejection);
return defer.promise;
}
};
});
and this is the authFactory:
.factory('AuthFactory', function($q, $http, $state,
LocalForageFactory, CONSTANT_VARS) {
return {
/**
* This function logs the customer, if the customer exists,
* Customer data is saved in order to perform actions,
* if not, an error message is returned.
* #param credentials a json with this format {username: 'jhon', password:'D03'}
* #returns {Animation.promise|promise}
*/
login: function(credentials) {
var defer = $q.defer(),
_this = this;
$http.post(CONSTANT_VARS.BACKEND_URL + '/auth/login',
credentials
).success(function(data) {
if (data.error) {
defer.reject(data);
}
_this.setCustomer(data).then(function(customer) {
defer.resolve(customer);
}, function(err) {
defer.reject(err);
});
}).error(function(data, status) {
if (status === 0) {
data = new Error('Backend is down');
data.raw = {};
}
defer.reject(data);
});
return defer.promise;
},
setCustomer: function(customer) {
var defer = $q.defer();
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_CUSTOMER, customer).then(function(customer) {
/*Removing LocalForage Items*/
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_LEAGUES);
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES);
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_SPORTS);
defer.resolve(customer);
}, function(err) {
$state.go('app.login');
defer.reject(err);
});
return defer.promise;
},
updateCustomer: function(customer) {
var defer = $q.defer();
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_CUSTOMER, customer).then(function(customer) {
defer.resolve(customer);
}, function(err) {
$state.go('app.login');
defer.reject(err);
});
return defer.promise;
},
getCustomer: function() {
var defer = $q.defer();
LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_CUSTOMER).then(function(customer) {
if (customer) {
defer.resolve(customer);
}else {
defer.reject(new Error());
}
defer.reject(customer);
}, function(err) {
defer.reject(err);
});
return defer.promise;
},
logout: function() {
var defer = $q.defer();
this.getCustomer().then(function(credentials) {
$http.post(CONSTANT_VARS.BACKEND_URL + '/auth/logout',
credentials
).success(function(data) {
if (data.error) {
defer.reject(data);
}
/*Removing LocalForage Items*/
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_LEAGUES);
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES);
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_SPORTS);
LocalForageFactory.remove(CONSTANT_VARS.LOCALFORAGE_CUSTOMER);
defer.resolve(data);
}).error(function(data) {
defer.reject(data);
});
}, function(err) {
$state.go('app.login');
defer.reject(err);
});
return defer.promise;
},
updateToken: function(token) {
var _this = this,
defer = $q.defer();
this.getCustomer().then(function(customer) {
customer.token = token;
_this.updateCustomer(customer).then(function(savedCustomer) {
defer.resolve(savedCustomer);
}, function(err) {
defer.reject(err);
});
}, function(err) {
defer.reject(err);
});
return defer.promise;
},
customerInfo: function() {
var defer = $q.defer();
this.getCustomer().then(function(customer) {
$http.post(CONSTANT_VARS.BACKEND_URL + '/auth/info', customer)
.success(function(data) {
defer.resolve(data);
})
.error(function(err) {
defer.reject(err);
});
}, function(err) {
defer.reject(err);
});
return defer.promise;
}
};
});

In app.js your doing SportsFactory.getSports() , but getSports expects 'agent' argument. Since you are not supllying it with 'agent' this: '/lines/sports/' + agent equals this: lines/sports/undefined, which is why you are getting 400 (bad request). There might be other things wrong with this code, but this is the reason for the error message.

Related

$q and resolving promises in Angular

I am not sure how to go about returning the promise. I have tried to return the result in a nested method but would prefer to return the result in two different methods as shown afterwards:
$scope.relatedContacts = function (accountId) {
if (!lodash.isNil(accountId)) {
try {
return restangular.one('user')
.one('contactimages')
.get({ 'mappedRelatedContactsPath': $scope.mappedRelatedContactsPath, "account": accountId })
.then(function (response) {
return response.data;});
}
}
Would prefer to fix the below example:
$scope.relatedContacts = function (accountId) {
if (!lodash.isNil(accountId)) {
try {
var deferred = $q.defer();
return restangular.one('user')
.one('contactimages')
.get({ 'mappedRelatedContactsPath': $scope.mappedRelatedContactsPath, "account": accountId })
return deferred.promise;
}
catch (err) {
$scope.contactsPopulated = false;
}
}
}
$scope.relatedContacts().then(function (response) {
//Some logic here
}
Currently I am getting : "TypeError: Cannot read property 'then' of undefined
"
Thanks all
First of all, remember about consistency. The isNil if makes your function not returning anything in some cases (you will get TypeError: Cannot read property 'then' of undefined " error when accountId is not provided.
You have two ways to solve your problem.
First way:
$scope.relatedContacts = function (accountId) {
return $q(function(resolve, reject) {
if (!lodash.isNil(accountId)) {
try {
return restangular.one('user')
.one('contactimages')
.get({ 'mappedRelatedContactsPath': $scope.mappedRelatedContactsPath, "account": accountId })
.then(function(response) {
resolve(response.data)
}, reject);
}
catch (err) {
$scope.contactsPopulated = false;
reject(err);
}
}
});
};
The second way (using defer).
$scope.relatedContacts = function (accountId) {
var def = $q.defer();
if (!lodash.isNil(accountId)) {
try {
restangular.one('user')
.one('contactimages')
.get({ 'mappedRelatedContactsPath': $scope.mappedRelatedContactsPath, "account": accountId })
.then(function(response) {
def.resolve(response.data)
}, def.reject);
}
catch (err) {
$scope.contactsPopulated = false;
def.reject(err);
}
}
return def;
};
You should check official reference about $q service:
https://docs.angularjs.org/api/ng/service/$q
There are numerous examples of typical promise usages.
This is what I used to return the value and add additional method to deal with the response.
$scope.relatedContacts = function (accountId) {
var deferred = $q.defer();
if (!lodash.isNil(accountId)) {
try {
deferred.resolve(restangular.one('user')
.one('contactimages')
.get({ 'mappedRelatedContactsPath': $scope.mappedRelatedContactsPath, "account": accountId }));
}
catch (err) {
$scope.contactsPopulated = false;
deferred.reject(err);
}
}
deferred.promise.then(function (response) {
var tests = response;
return $q.when();
},
function () {
console.log("1st reject");
return $q.reject();
});
return deferred.promise;
};

How to handle a call back hell in $http chaining?

I have many $http requests as following:
Scholarship.loadMaxAcademicYear().success(function (AcademicYearId) {
if (AcademicYearId) {
Scholarship.deleteAllCurrentData(data).success(function () {
Scholarship.copyDataToCurrentYear().success(function(){
Scholarship.getPromises(null, AcademicYearId).then(function () {
$scope.isSuccess = true;
$timeout(function () {
$scope.isSuccess = false;
$scope.isSubmit = false;
$scope.confirmModal.close();
}, 5000);
}, function(err){
importError();
});
}).error(function(){
importError();
})
}).error(function(){
importError();
});
}
}).error(function (err) {
importError();
});
I want to reduce the error callback to be only one at the end as following:
Scholarship.loadMaxAcademicYear().success(function (AcademicYearId) {
if (AcademicYearId) {
Scholarship.deleteAllCurrentData(data).success(function () {
Scholarship.copyDataToCurrentYear().success(function(){
Scholarship.getPromises(null, AcademicYearId).then(function () {
$scope.isSuccess = true;
$timeout(function () {
$scope.isSuccess = false;
$scope.isSubmit = false;
$scope.confirmModal.close();
}, 5000);
}
})
})
}
}).error(function (err) {
importError();
});
I'm thinking of using the async but Angular might have some way to handle this kind of problem. Would it be possible to do so in AngularJs?
You've still got a pyramid of doom even in your second example. The key here is to use the .then() method to allow promise chaining:
Scholarship.loadMaxAcademicYear().then(function(response) {
var academicYearId = response.data;
if (academicYearId) {
return Scholarship.deleteAllCurrentData(academicYearId)
.then(function() {
return Scholarship.copyDataToCurrentYear();
}).then(function() {
return Scholarship.getPromises(null, academicYearId);
}).then(function() {
$scope.isSuccess = true;
return $timeout(function() {
$scope.isSuccess = false;
$scope.isSubmit = false;
$scope.confirmModal.close();
}, 5000);
});
}
}).catch(function(err) {
importError();
});
We can also shorten this a bit by using .bind():
Scholarship.loadMaxAcademicYear().then(function(response) {
var academicYearId = response.data;
if (academicYearId) {
return Scholarship.deleteAllCurrentData(academicYearId)
.then(Scholarship.copyDataToCurrentYear.bind(Scholarship))
.then(Scholarship.getPromises.bind(Scholarship, null, academicYearId))
.then(function() {
$scope.isSuccess = true;
return $timeout(function() {
$scope.isSuccess = false;
$scope.isSubmit = false;
$scope.confirmModal.close();
}, 5000);
});
}
}).catch(importError);

how can I put an item with checked = true depending on the info in the DB?

I have a list of items with the option to checked or unchecked them. I am doing a post request in order to save the unchecked items, and that post request works great, but I am having an issue with the get request, the front-end retrieves fine the info from the back-end, but I have this function which is putting on checked = true the items without taking care of the unchecked items saved already
if (sports.length) {
$scope.sports = _.map(sports, function(sport) {
sport.checked = true;
return sport;
});
};
so, if the user refreshes the page, all items get back to checked = true due to the function above. So how can I do to persist the items with checked or unchecked ? what do I have to change in that function in order to persist that data ?
this is my code regarding the get request of that data
I am using lodash, just in case...
front-end
controller.js
please read the note in this code
.controller('SportsController', function($scope, SportsFactory, AuthFactory) {
$scope.sports = [];
SportsFactory.getSportChecked(customer).then(function(sportChecked) {
_.each(sports, function(sport) {
var sportIds = _.pluck(sports, 'id'),
intersectedSports = _.intersection(sportIds, sportChecked),
checkedSportObjects = _.filter(sport, function(sportObj) {
return _.includes(intersectedSports, sportObj);
});
_.each(checkedSportObjects, function(sport) {
$scope.sports.push(sport);
});
});
}
//this is the function putting checked = true with out taking care
//of what the back-end returns
if (sports.length) {
$scope.sports = _.map(sports, function(sport) {
sport.checked = true;
return sport;
});
}
$scope.toggleSportSelection = function(sport) {
var params = {};
params.user = $scope.customer.customer;
params.sport = sport.id;
sport.checked = !sport.checked;
SportsFactory.setSportChecked(params);
};
});
service.js
.factory('SportsFactory', function($http, $q, AuthFactory,
LocalForageFactory, CONSTANT_VARS) {
return {
getSportChecked: function(customer) {
var defer = $q.defer(),
user,
rejection = function(err) {
console.log(err);
defer.reject(err);
};
LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_SPORTS_CHECKED)
.then(function(sportChecked) {
user = customer.customer;
if (!_.isNull(sportChecked)) {
defer.resolve(sportChecked);
}else {
$http.get(CONSTANT_VARS.BACKEND_URL + '/sports/getChecked/' + user)
.success(function(sportChecked) {
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_SPORTS_CHECKED, sportChecked);
defer.resolve(sportChecked);
})
.error(rejection);
}
}, rejection);
return defer.promise;
}
}
});
BACK-END - node.js/sails.js
SetSportsController
module.exports = {
retrieveSetCheck: function(req, res) {
if (req.params) {
SportSelectionService.getSportChecked(req.params).then(function(sportChecked) {
res.json(200, sportChecked);
}, function(err) {
res.json(400, err);
});
}else {
res.json(400, {error: 'Error retrieving Sports'});
}
}
}
SportSelectionService
module.exports = {
getSportChecked: function(params) {
var Promise = require('bluebird');
return new Promise(function(fullfill, reject) {
console.time('sportChecked_findOne');
SportSelection.find({
user: params.user
}).exec(function(err, sportChecked) {
console.timeEnd('sportChecked_findOne');
if (err) {
reject(new Error('Error finding sportChecked'));
console.error(err);
}else {
if (sportChecked) {
fullfill(sportChecked);
}else {
console.time('sportChecked_create');
SportSelection.create({
sport: [],
user: params.user
}).exec(function(err, created) {
console.timeEnd('sportChecked_create');
console.log(err);
console.log(created);
if (err) {
reject(new Error('Error on sportChecked'));
}else {
fullfill(created);
}
});
}
}
});
});
}
}

Angular js - resolving promises in routeProvider [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm just trying resolving promises from a factory like this:
.config(['$routeProvider', '$locationProvider', '$httpProvider', 'SoundRTCProvider', function ($routeProvider, $locationProvider, $httpProvider, SoundRTCProvider) {
$routeProvider
.when('/',{
templateUrl:'views/home/index.html',
controller:'Home',
resolve: {
load: function (configFactory) {
return configFactory.loadAll();
}
}
});
});
then :
.factory('configFactory',['$rootScope', '$q', '$location', '$anchorScroll', '$routeParams', 'ngDialog', 'cacheService', 'sessionFactory', 'geoFactory', 'instrumentsFactory', 'genresFactory', 'langFactory', 'usersFactory', 'contactsFactory', function ($rootScope, $q, $location, $anchorScroll, $routeParams, ngDialog, cacheService, sessionFactory, geoFactory, instrumentsFactory, genresFactory, langFactory, usersFactory, contactsFactory) {
var initConfig = function () {
var deferred = $q.defer();
/*CONFIG PARAMS*/
$rootScope.config = {};
$rootScope.config.appWs = '';
$rootScope.config.appName = 'Dunno';
deferred.resolve('go');
return deferred.promise();
};
var initUserSession = function () {
var deferred = $q.defer();
/*----- INIT USER SESSION ---*/
$rootScope.session = {};
/*RELOAD SESSION if logged*/
if(sessionFactory.get('idUser')){
usersFactory.getMyProfile().then(function(results){
sessionFactory.initSession(results.data);
deferred.resolve();
});
}
return deferred.promise();
};
var initGravatar = function () {
var deferred = $q.defer();
/*------- INIT GRAVATARS ------*/
$rootScope.gravatar = {};
deferred.resolve();
return deferred.promise();
};
var initLang = function () {
var deferred = $q.defer();
/*------LANGUAGE---------*/
$rootScope.userLang = 'en_EN';
$rootScope.lang = {};//get key and value from here in views
//If user lang doesn't exists yet
if(cacheService.isExpired('appLang')) {
langFactory.getAll($rootScope.userLang)
.then(function (response) {
if(angular.isObject(response.data) && Object.keys(response.data).length > 0) {
cacheService.put('appLang',response.data,$rootScope.config.minChacheTime);
$rootScope.lang = cacheService.get('appLang');
} else {
$rootScope.lang = cacheService.get('appLang');
}
deferred.resolve();
});
} else {
deferred.resolve();
$rootScope.lang = cacheService.get('appLang');
}
return deferred.promise();
};
var initGenres = function () {
var deferred = $q.defer();
/*-------GENRES-------*/
if(cacheService.isExpired('appGenres')) {
genresFactory.getAll()
.then(function (response) {
if(angular.isObject(response.data) && Object.keys(response.data).length > 0) {
cacheService.put('appGenres',response.data,$rootScope.config.minChacheTime);
$rootScope.config.appGenres = cacheService.get('appGenres');
} else {
$rootScope.config.appGenres = cacheService.get('appGenres');
}
deferred.resolve();
});
} else {
deferred.resolve();
$rootScope.config.appGenres = cacheService.get('appGenres');
}
return deferred.promise();
};
var initInstruments = function () {
var deferred = $q.defer();
/*------INSTRUMMENTS------*/
if(cacheService.isExpired('appInstruments')) {
instrumentsFactory.getAll()
.then(function (response) {
if(angular.isObject(response.data) && Object.keys(response.data).length > 0) {
cacheService.put('appInstruments',response.data,$rootScope.config.minChacheTime);
$rootScope.config.appInstruments = cacheService.get('appInstruments');
} else {
$rootScope.config.appInstruments = cacheService.get('appInstruments');
}
deferred.resolve();
});
} else {
deferred.resolve();
$rootScope.config.appInstruments = cacheService.get('appInstruments');
}
return deferred.promise();
};
var initGeo = function () {
var deferred = $q.defer();
/*-------GEO----------*/
if(cacheService.isExpired('appGeo')) {
geoFactory.getAll()
.then(function (response) {
if(angular.isObject(response.data) && Object.keys(response.data).length > 0) {
cacheService.put('appGeo',response.data,$rootScope.config.minChacheTime);
$rootScope.config.appGeo = cacheService.get('appGeo');
} else {
$rootScope.config.appGeo = cacheService.get('appGeo');
}
deferred.resolve();
});
} else {
deferred.resolve();
$rootScope.config.appGeo = cacheService.get('appGeo');
}
return deferred.promise();
};
var initUserContacts = function () {
var deferred = $q.defer();
/*CONTACTS*/
$rootScope.contacts = {
approved: [],
pending: []
};
if(sessionFactory.get('idUser')){
contactsFactory.getMine().then(function (res) {
if(angular.isArray(res.data) && res.data.length > 0) {
for(var i in res.data) {
//set all my pending contacts
if(res.data[i].approved !== 1) {
$rootScope.contacts.pending.push(res.data[i].idContact);
} else {
//set all my contacts
$rootScope.contacts.approved.push(res.data[i].idContact);
}
}
}
deferred.resolve();
});
} else {
deferred.resolve();
}
return deferred.promise();
};
var initLayout = function () {
var deferred = $q.defer();
/*LAYOUT*/
$rootScope.layout = {
loading:true,
userMenu:false
};
deferred.resolve();
return deferred.promise();
};
var initScroll = function () {
var deferred = $q.defer();
//Make app scroll to top by default while navigating or use #anchor in url like http://sitess.com/someroute/?scrollTo=<:idelement:> to make it scroll to that element :id:
$location.hash($routeParams.scrollTo);
$anchorScroll();
deferred.resolve();
return deferred.promise();
};
var initDialog = function () {
var deferred = $q.defer();
//Close any dialog
ngDialog.close();
deferred.resolve();
return deferred.promise();
};
var loadAll = function () {
var deferred = $q.defer();
initConfig()
.then(function(){
return initUserSession();
}).then(function () {
return initLang();
}).then(function () {
return initGenres();
}).then(function () {
return initGeo();
}).then(function () {
return initInstruments();
}).then(function () {
return initUserContacts();
}).then(function () {
return initGravatar();
}).then(function () {
return initLayout();
}).then(function () {
return initScroll();
}).then(function () {
return initDialog();
}).then(function () {
$rootScope.$on('loading:end', function(){
$rootScope.layout.loading = false;
});
$rootScope.$on('loading:progressing', function (){
$rootScope.layout.loading = true;
});
$rootScope.$on('$locationChangeError', function () {
//hide loading gif
$rootScope.layout.loading = false;
//hide loading gif
$rootScope.layout.userMenu = false;
});
//all done with configs
deferred.resolve();
});
return deferred.promise();
};
return {
initConfig:initConfig,
initUserSession:initUserSession,
initLang:initLang,
initGenres:initGenres,
initGeo:initGeo,
initGravatar:initGravatar,
initInstruments:initInstruments,
initUserContacts:initUserContacts,
initLayout:initLayout,
initScroll:initScroll,
initDialog:initDialog,
loadAll:loadAll
};
}]);
What's up why do i get Error in console : TypeError: object is not a function
at initConfig (assets/js/factories.js:35:23)
that means the first return deferred.promise(); is generating the error, i can't understand whats wrong, any help appriciated thanks
You are trying to execute a normal object as a function (which is what the error means). It should be: return deferred.promise; instead of: return deferred.promise();.

Angular Testing controller with factory

Hello I have this controller that handles login:
angular.module('fancyApp')
.controller('MainCtrl', function ($scope, $location, $http, LoginFactory) {
$scope.loginForm = function(isValid) {
if (isValid) {
var status;
LoginFactory.login($scope.person).then(function(d) {
console.log(d);
$scope.data = d;
if (d.status === 200) {
//login success
$('.loginFail').hide();
$location.path('/student');
} else {
$scope.loginFail = 'Failed to login';
$('.loginFail').show();
}
});
} else {
$scope.login_form.submitted = true;
}
};
});
And this is my LoginFactory login function:
angular.module('fancyApp')
.factory('LoginFactory', function ($http, $q) {
return {
login: function(user) {
var promise = $http.post( 'api/v1/login', user).then(function (response) {
return response;
}, function(error) {
return error;
});
return promise;
};
});
This is my beforeEach:
beforeEach(inject(function ($controller, $provide, $location, $rootScope) {
location = $location;
rootScope = $rootScope;
var testService = {
getStudents: function() {
return ['student1', 'student2'];
},
getAdmins: function() {
return ['admin1', 'admin2'];
},
login: function(person) {
console.log(testService.getStudents().indexOf(person.user));
if(testService.getStudents().indexOf(person.user) !== -1) {
return {status:200, token:'xxx', role:'student'};
}
else if(testService.getAdmins().indexOf(person.user) !== -1) {
return {status:200, token:'xxx', role:'admin'};
}
else {
return {status:401, token:'xxx', role:'student'};
}
}
};
scope = $rootScope.$new();
$provide.service('LoginService', testService);
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
And here is my test:
it('Login should succeed', inject(function($httpBackend){
spyOn(testService, 'login');
scope.person.user = 'student1';
scope.person.pass = '123456';
scope.login(true);
expect(testService.login).toHaveBeenCalledWith('student1', '123456');
}));
The error I get is:
Error: [$injector:unpr] Unknown provider: $provideProvider < $provide
I'm not sure if this is the correct way of testing this, any suggestions would be nice.
Thank you.
You can't use $provide within the inject function because the former registers providers for the latter to use. Do it like this:
describe('...', function() {
beforeEach(function() {
module(function($provide) {
$provide.service('LoginService', testService);
});
inject(function(someValue) {
//Rest of the code within the inject..........
});
});
});

Categories