How do I test a string's values in Jasmine? - javascript

I have a string that is used to display text. It is initially set to null, then is updated throughout a function with status updates. I want to make sure the string is set to the correct status updates throughout the function's lifetime.
Jasmine's spies seem focused on testing functions and their interactions. I specifically want to test a string's history. Assuming the following code:
(function() {
$this.loggingIn = false;
$this.submit = function () {
$this.loggingIn = "Requesting access...";
$this.errorMessage = "";
var aThing = {};
var aSecondaryThing = {};
$http.post(aThing)
.success(function (data, status, headers, config) {
$this.loggingIn = "Validating credentials...";
$http.post(aSecondaryThing)
.success(function (data, status, headers, config) {
$this.loggingIn = "Done!";
})
.error(function (data, status, headers, config) {
$this.errorMessage = data.error_description || "Invalid username or password.";
$this.loggingIn = false;
});
})
.error(function (data, status, headers, config) {
$this.errorMessage = data.error_description || "Invalid username or password.";
$this.loggingIn = false;
});
return false;
};
})();
This function is abridged from our original Angular code. Nothing's missing aside from the wiring to make the controller work and the post actions.
Is there a way to test that loggingIn is set to "Validating credentials..." and then "Done!" without writing a setter function to handle it?

Ultimately we went with a setter function to handle the string management and testing. Although testing what the string actually says probably isn't needed, at the time it was required enough to need verification. That way we can verify if the function was being called, and then later verify the function changes the string correctly, which is proper testing in any case.

Related

Angular success function called before http.get function returns

I have an angular controller which makes an HTTP GET request and on the promise return, calls either a success of error function. My code right now will sometimes execute the success function after the GET request returns and sometime execute before it. Is there something I'm messing up in my promise handling? Something to note, sometimes the http GET doesn't even get called (or at least its breakpoint) and the success function happens regardless. Here is my code:
.controller('CheckOutCtrl', ['$scope', '$http', function($scope, $http) {
//Controller for checkout feature
$scope.owner = "Unclaimed"; //Default owner
$scope.endDate = "";
$scope.unclaimed = true;
$scope.showpopup = false; //Should we show the popup that checkout is successful or returned
$scope.currentOwner = false; //Show return date
$scope.popuptext = "";
$scope.checkOut = function(){ //Extends or creates a check out
$http.get("/checkout/extend/code/" + code + "/username/" + userName).then(
function success(response, status, headers, config) {
console.log("Checked out or extended");
$scope.showpopup = true;
$scope.currentOwner = true;
$scope.popuptext = response.data; //Show airport checked out until or error
console.log($scope.popuptext);
init(); //Update current owner
},
function error(response, status, headers, config) {
$scope.error = response;
console.error("Check out error:", response);
}
);
};
}
I discovered this was happening because Angular caches GET requests for some time and the cached version of my request was being used.

Error in returning java object to javascript

I am returning a java object to client(javascript) page, i.e. converting java object to JSON object but am facing no converter found for return value error.
I have added all spring jars and jackson-all-xxx.jar.
The below is the method that gets called from a html page using $http.get('url').
#RequestMapping(value="/springAngularJS",method=RequestMethod.GET)
public #ResponseBody Person getPerson() {
System.out.println("111111111");
Person person = new Person();
person.setFirstName("Java");
person.setLastName("Honk");
return person;
}
My html page: (posting only JS part)
var app = angular.module('myApp', []);
function MyController($scope, $http){
$scope.getPersonDataFromServer = function() {
$http.get("springAngularJS").
success(function(data, status, headers, config) {
$scope.person = data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
};
Any help to resolve this would be appreciated..
I am a beginner..:)
Your problem is with project dependency and not code , as the above code is correct .
Again I suggest on you to start with Spring-boot it will allow you to concentrate on the code only working example

AngularJS Form/HTTP/CORS

I have an Angular form connected to a REST API to insert a new row to a MySQL database. My REST API is working, but I am getting a CORS blocked notice in my web console. How can I get it to successfully send to the REST PI? Below is my controller code code:
countryApp.controller('AddLocation', function ($scope, $http) {
$scope.orglocation = {};
//
$scope.submit = function() {
var dataObj = {
location_title : $scope.location.location_title,
location_latitude : $scope.location.location_latitude,
location_longitude : $scope.location.location_longitude
}
//convert data to JSON string
var loc = JSON.stringify(dataObj);
$http.post('http://localhost/slimtest2/add_location', loc).
success(function(data, status, headers, config) {
alert("good");
}).
error(function(data, status, headers, config) {
alert("bye");
});
}
$scope.reset = function() {
$scope.location = angular.copy($scope.orglocation);
}
});
Generally when you hit a CORS problem it is a sign that your server is not configured correctly. I highly suggest looking at the MDN article on HTTP access control. The two headers that are most important to have in this case are:
access-control-allow-origin
access-control-allow-methods
Make sure the first is set to the domain and port you use to access your Angular app and that the second is set to the methods you use (in this case, at least POST).

Putting an error function in angular javascript

My javascript function is working in angular, but I want to have an error function to determine of there is an error when a bad request is sent. How could I put the error function in this kind of format of code in javascript? Thanks in advance to those who want to help me.
$scope.submitLogin = function()
{
var request = {};
request.url = '/account/users/login';
request.method = 'POST';
request.data = angular.toJson($scope.students);
var onSuccess = function(data, status, headers, config, statusText)
{
alert('success!');
$location.url('/examdirection/');
};
httpRequest(request, $scope.response, onSuccess);
};

When I “Pull to refresh”, How I clean the Cache? With Ionic Framework and AngularJS

I have a problem, I'm using a JSON coming from an external server, but when I do "Pull to refresh" or when I open the application, displays the same information I downloaded the first time the application is opened. It may be that the JSON is being stored in the cache and therefore not update? For if when I go to on-refresh = "doRefresh ()" and called another JSON, (the first time I do), update, but re-enter the application I load the information from the first JSON and if I want update, showing me the information I also downloaded the first time. This will fix manually deleting the application data, but it is not the best way ...
This is my services.js
angular.module('starter.services', ['ngResource'])
.factory('NotasService', ['$http',
function ($http) {
var items_nota = [];
var items_nota_array;
return {
all: function () {
return $http.get('http://192.168.1.0:8100/wp-json/posts?filter[post_status]=publish&filter[posts_per_page]=30')
.success(function(data, status, headers, config){
console.log("**** SUCCESS ****");
console.log(status);
})
.error(function(data, status, headers, config){
console.log("**** ERROR ****");
console.log(status);
})
.then(function(response){
console.log("**** THEN ****");
items_nota = response;
return items_nota;
}
)
},
get: function (notaId) {
// Simple index lookup
var pepe = parseInt(notaId);
var ESTO = 0;
var addToArray = true;
for (var i = 0; i < items_nota.length; i++) {
if (items_nota[i].id == pepe) {
addToArray = false;
ESTO = i;
}
}
return items_nota[ESTO];
}
}
}])
This is my controller.js..
.controller('ActulidadCtrl', function ($q, $scope, NotasService, $timeout) {
var items_nota;
NotasService.all().then(function (data) {
$scope.items_nota = data;
})
//Pull tu refresh
$scope.doRefresh = function () {
console.log('Actualizando!');
$timeout(function () {
//NotasService.loadData().then(function (data) {
NotasService.all().then(function (data) {
$scope.items_nota = data;
})
//Stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
});
};
})
Thanks! And Happy New Year!
UPDATE: solved the problem was in the server side cache
I think your problem is with GET query:
http://192.168.1.0:8100/wp-json/posts?filter[post_status]=publish&filter[posts_per_page]=30
Please check if this query is returning same posts event if you add new data.You can make sample http query using tools like Postman.
post_status and posts_per_page are constant.
Please check. Good luck!!

Categories

Resources