Unit Testing Angular Js with Jasmine - javascript

I have a piece of angular code that does a post request to the cloudant, returns a response, builds a URL with it and does a get request with the same. The get request returns an array buffer through which i build a PDF file to be rendered in the front end.
Could someone please let advice me on how to unit test this as unit testing along with rest API is a new territory for me . PFB my code
$scope.viewfile = function(name) {
$http({
method : 'POST',
url : '/search/searchFiles',
data : {'currentdropdownvalue' : name} ,
}).
success(function(data){
if (!angular.isUndefined(data.docs[0])){
$scope.file = data.docs[0]._id;
var fileUrl = $scope.cloudantUrl + $scope.file +"/"+ $scope.file;
$http.get(fileUrl {responseType:'arraybuffer'})
.success(function (response) {
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
$scope.contentType = "application/pdf";
$scope.contentWords = null;
}).error(function(data){
console.log("Printing Error inside Post of view " , data);
});
}
else{
$scope.content = null;
$scope.contentWords = "File is not available for the selected Name";
}
}).
error(function(data){
console.log("Printing Error inside view " , data);
});
};
}

Ideally you should probably use $httpBackend but I usually just end up putting a spy on these functions. Heres some sudo code using spyOn:
it('Should test viewFile', function() {
spyOn($http, 'POST').andReturn(mock_data);
spyOn($http, 'GET').andCallFake(function(fileUrl) {
expect(fileUrl).toBe($scope.cloudantUrl + $scope.file +"/"+ $scope.file);
});
$scope.viewFile(mocked_name).then(function() {
expect($scope.content).toBe($sce.trustAsResourceUrl(fileURL));
expect($scope.contentType).toBe("application/pdf");
expect($scope.contentWords.toBe(null);
});
$rootScope.$apply();
});

Related

AngularJS $location.search() doesn't return anything

I am using AngularJS 1.6.4
The url of my homepage is http://localhost:8080/AsumForum/
I am trying to display a success message if user has registered successfully to my web site. If the user is registered, I will redirect him to the home page, and my url looks like this: http://localhost:8080/AsumForum/?registered=true.
The thing is, $location.search() never finds registered=true. I have tried making $locationProvider compatible with HTML5, but that doesn't work either.
Here is my registration.js:
var app = angular.module('reg',[]);
app.controller('valid', ['$scope','$location','$http',
function($scope,$location,$http){
$scope.send = function(){
var date = new Date();
$scope.user.date=date.toString();
$http({
url: 'http://localhost:8080/AsumForum/webapi/users/register',
dataType: 'json',
method: 'POST',
data: $scope.user,
headers: {
"Content-Type": "application/json"
}
}).then(function success(response){
$scope.res = response.data;
$scope.satus = response.status;
console.log('RES: '+$scope.res+'\nSTATUS: '+$scope.status);
window.location="http://localhost:8080/AsumForum/?registered=true";
}, function error(response){
$scope.res = response.statusText;
console.log('Error: +'+$scope.res);
});
}
}]);
And here is my login.js
var app = angular.module('mainPage',[]);
app.controller('regsuc',['$scope','$location',function($scope,$location){
$scope.message = '';
var show = $location.search();
for(var i in show){
console.log(i);
}
if(show==true){
$scope.message="Successfull registered! You can now log in.";
}
}]);
Logs don't return anything. Using console.log(show) returns [object Object].
Do I really have to use routing to pass parameters, or can it be done like I tried?
Note 1: Redirecting with $location.url('http://localhost:8080/AsumForum/?registered=true); doesn't work for me.
Note 2: Using location.search instead of $location.search returns ?registered=true.
Just try the following
you have missed the parameter name in $location.search()
$location.search().registered

Loading XML File with Angular

I have Web Api calls that I make via angular $http , What I need to do are some various options.
Call Web Api endpoint which will then create an XML file on the file system of which I need to be able to have my Angular application display the XML in another window - would this be done a specific way with angular?
Like to Also be able to stream in memory the xml to be in angular as a string for me to decide how to parse thoughts?
I do see code like below, which is "nice" , but I don't want to just convert xml to json
angular.module('myApp',[]).factory('DataSource', ['$http',function($http){
return {
get: function(file,callback,transform){
$http.get( file, {transformResponse:transform} ).
success(function(data, status) {
console.log("Request succeeded", data);
callback(data);
}).error(function(data, status) {
console.log("Request failed " + status);
});
}
};
}]);
var AppController = function($scope,DataSource) {
var SOURCE_FILE = "timer.xml";
xmlTransform = function(data) {
console.log("transform data");
var x2js = new X2JS();
var json = x2js.xml_str2json(data);
return json.TimerStatus;
};
setData = function(data) {
console.log("setdata", data);
$scope.dataSet = data;
};
DataSource.get(SOURCE_FILE,setData,xmlTransform);
};

AngularJS - $http.get request gets cancelled

I'm trying to get data from a server in my AngularJS app, using $http.get. But when I execute the request, it seems to get cancelled by something. It happens with every link I use. Local files are working.
Below the code from Controller.js:
angular
.module('schoolApp')
.controller('configController', [
'apiService', '$http', function (apiService, $http) {
var vm = this;
vm.isActive = isActive;
vm.addPortal = addPortal;
...
function addPortal() {
...
apiService.getServerData('someUrl', "1.0")
.then(function (result) {
var test = result.data;
})
.catch(function (result) {
console.log(result);
});
}
...
And the Service.js:
angular
.module('schoolApp')
.service('apiService', [ '$http', function ($http) {
var service = {
getServerData: getServerData,
};
return service;
function getServerData(portalUrl, appVersion) {
// var url = "http://../.../.svc/GetSetting?alias=...&AppVersion=1.0";
var url = "http://xml.buienradar.nl";
//var url = "test.json";
//var url = "xml.xml";
// "http://" +
// portalUrl +
// "/.../.../.svc/GetSetting?alias=" +
// portalUrl +
// "&AppVersion=" +
// appVersion;
return $http.get(url);
}
}]);
Executing this code will show the alert("ERROR: " + result) from the controller class. Data from the result:
result: Object config: Object data: null headers: (c)
status: -1 statusText: ""
__proto __: Object
Network in browser shows the call is cancelled:
http://i.stack.imgur.com/MJoZM.png
More info:
- I'm using Phonegap (tested without and doesn't work either)
- AngularJS 1.4
Ok, found the answer. I called window.location.reload() in the same function, and that conflicted. So, now I added it to the .then() function in the request.

Returning success using res.send

I am using combination of Node and Angualr JS alongwith express-4
In my code I am trying to send newSourceId via res.send . I am able to get the newSourceId but when I send it using res.send it gets into error instead of getting in to success.
I also tried using res.sendStatus(newSourceId) but no luck!
Following is the Node JS part:
app.post('/addObservationDetail',function(req,res){
var newSourceId = -1;
Observation.create({obv_source:req.body.source,obv_waveband:req.body.waveband,prpsl_id:req.body.pId}
).then(function(result) {
Observation.findAll({
attributes: [['obv_id','id']],where:{prpsl_id:req.body.pId},order: [["obv_id","DESC"]],limit: 1
}) .then(function(rows) {
console.log("Obv_Id is = "+rows[0].dataValues.id);
newSourceId=rows[0].dataValues.id;
console.log("newsrc===="+newSourceId);
res.send(newSourceId);
});
});
});
This is the Angular JS part:
$scope.updateObsDet = function(obs_detail,index) {
var url = "/";
if(obs_detail.sourceId == null){
url += "addObservationDetail";
$http({
method:'POST',
url:url,
headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest:function(obj){
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data:{source:obs_detail.source,waveband:obs_detail.waveband,pId:$scope.proposal.proposalId}
}).success(function(data){
alert("New observation added"); //should come in here
updateSourceId(data,index,obs_detail);
}).error(function(data){
alert(data); //getting in here
});
} else {
url += "updateObservationDetail";
data = {
source:obs_detail.source,
waveband:obs_detail.waveband,
sourceId:obs_detail.sourceId
};
$http.post(url,data).success(function(data){
alert(data);
}).error(function(data){
alert(data);
});
}
};
PS: I can not change the angular Part of the code, changes need to be done in the Node JS part.
yes you can set json response try this
var http = require('http');
var app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ a: 1 }));
});
app.listen(3000);

How to connect jsReport in AngularJS?

I have a problem now about JSReport.. It assumed that I already have an API...What I want now is how to link it with my Client Side which uses AngularJS.
If I use Postman it will return a pdf file which is what I want. But my problem is how to show it is my page when i post it using angularjs..
I have a code like this :
Controller
$scope.Print = function () {
authService.print().then(function(result){
var _result = result;
});
};
Service
var _print = function () {
var data = { "template": { "shortid": "byQtwHLPQ" } };
return $http.post("http://192.168.8.87/api/report", data).then(function (result) {
return result;
});
};
authServiceFactory.print = _print;
Now I have that Code and its not working... I assumed it has no return so I remove the return and just post but still it didn't work and even downloading the pdf didn't work on it.
Anyone can help Please...
Use like this one..
Controller
var parameter = { "template": { "shortid": "ZkMoslfdX" }};
PrintService.Print(parameter).then(function (result) {
var file = new Blob([result.data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
});
Service
var reportUrl = "http://192.168.8.87/api/report";
var _print = function (parameter) {
return $http.post(reportUrl, parameter, { responseType: 'arraybuffer' }).success(function (response) {
return response;
});
};
The main idea is that the result.data is converted into a blob and create an objectURL so that it is readable and to the object tag and $sce.trustAsResourceUrl used to trust angular to your URL
HTML
<object data="{{content}}" type="application/pdf" style="width:100%;height:80%"></object>
I refer to this post AngularJS: Display blob (.pdf) in an angular app for clarification just read that one.

Categories

Resources