In this example, I have an e2e test doing a button click, which executes a function that does a POST
I would like to be able to have access to the "data" object from testDev httpBackend callback, in my e2e scenerios code, for verification.
Is this possible in an e2e test? If so, could you point me in the right direction?
thanks
scenerio code
describe('test2 app', function() {
beforeEach(function() {
browser().navigateTo('/testbed/e2e/app/index2.html');
});
it('should run a POST',function() {
element('#myButton2').click();
});
});
test module
var test2Dev = angular.module('test2Dev', ['test2App', 'ngMockE2E'])
.run(function($httpBackend) {
$httpBackend.whenPOST(/testpost/)
.respond(function(method, url, data, headers){
console.log(data);
return [200, data, {}];
});
});
markup
<html lang="en" ng-app="test2Dev" ng-controller="test2Ctrl">
<head>
<meta charset="utf-8">
<title>Test click </title>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" href="css/bootstrap.css">
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-mocks.js"></script>
<script src="/testbed/e2e/test/e2e/test2Dev.js"></script>
<script src="js/controllers2.js"></script>
</head>
<body>
<button id="myButton2" ng-click="runPost()">run post</button>
</body>
</html>
controller
var test2App = angular.module('test2App', []);
test2App.controller('test2Ctrl', function($scope,$http) {
$scope.runPost = function() {
$http.post('/testpost',{
data1 : 'chevy',
data2 : 'ford'
});
}
});
runner
<!doctype html>
<html lang="en">
<head>
<title>End2end Test Runner</title>
<meta charset="utf-8">
<base href="../..">
<script src="app/lib/angular/angular-scenario.js" ng-autotest></script>
<script src="app/lib/angular/angular-mocks.js" ng-autotest></script>
<script src="/testbed/e2e/test/e2e/test2Dev.js"></script>
<script src="/testbed/e2e/test/e2e/scenarios2.js"></script>
</head>
<body>
</body>
</html>
Not very pretty but I removed my test module, and used a changed version of "mockApi" here->
https://github.com/blabno/ngMockE2E-sample (thank you Bernard Labno)
changed e2e.mocks.js to add the data object to it's config obj->
function setup(method, url, config)
{
$httpBackend.when(method, url).respond(function (requestMethod, requestUrl, data, headers) {
config.triggered = true;
config.data = data;
var response = config.response || {};
if (config.serverLogic) {
response = config.serverLogic(requestMethod, requestUrl, data, headers);
}
return [response.code || 200, response.data];
});
}
setup(POST, /testpost/, mocks.api.post_test);
.... and added this method to access it....
chain.getData = function() {
return this.addFuture("get data object for " + itemName, function(done) {
done(null,JSON.parse(api[itemName].data));
});
};
... here is my scenerio now...
it('should run a POST',function() {
element('#myButton2').click();
expect(mockApi("post_test").getData()).toEqual({
data1 : 'chevy',
data2 : 'ford'
});
});
Is there a better way to do this?
Related
Hi i wondering that ploblem so i want ask somebody
so please give me solution?
I make html file like that photo
but when i open this html file this file not working…
any data not diplay
what is the ploblem in this html file?enter image description here
<!doctype html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<div ng-controller="QueryController">
</div>
<script src="node_modules/angular/angular.js"></script>
<script src="node_modules/elasticsearch-browser/elasticsearch.angular.js"></script>
<script>
var myApp = angular.module('myApp', ['elasticsearch']);
// Create the es service from the esFactory
myApp.service('es', function (esFactory) {
return esFactory({ host: 'localhost:9200'});
});
myApp.controller('ServerHealthController', function($scope, es, esFactory) {
es.cluster.health(function (err, resp) {
if (err) {
$scope.data = err.message;
} else {
$scope.data = resp;
}
});
});
// We define an Angular controller that returns query results,
// Inputs: $scope and the 'es' service
myApp.controller('QueryController', function($scope, es, esFactory) {
// search for documents
es.search({
index: 'epowersyst',
type: 'logs',
body: {
query:
{
match_all : {} }
}
}).then(function (response) {
$scope.hits = response;
console.log($scope.hits)
alert("hits값 : " + response);
});
});
</script>
</body>
</html>
How should i access URL json array data using angular.forEace.
i am trying to get data but giving some error please check below code i have added
[{
"flightsDepartur":[
{
"fare":"9,000",
"route":[
{
"source":"Delhi",
}
],
},
]
}]
$http.get('data.json').then(function(response) {
$scope.allData = response;
},function(dataStatus){
console.log(dataStatus);
});
angular.forEach($scope.allData, function(flidata) {
angular.forEach(flidata[0].flightsDepartur, function(flidatIn) {
console.log(flidatIn.fare);
});
});
check the below to get fare and route data
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = [{
"flightsDepartur":[
{
"fare":"9,000",
"route":[
{
"source":"Delhi",
}
],
},
]
}];
angular.forEach($scope.name, function(k,v) {
angular.forEach(k, function(k,v) {
console.log(k[0].fare);
console.log(k[0].route[0].source)
});
});
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
</body>
</html>
The problem is you are assigning values to $scope.allData inside a promise. since the javascript asynchronous before the data being assign to $scope.allData for each loop start to execute. at that time $scope.allData was undefined. so it produces an error.
create a function and call that inside the promise to prevent the error
$http.get('data.json').then(function(response) {
$scope.allData = response.data;
callLoop()
},function(dataStatus){
console.log(dataStatus);
});
function callLoop(){
angular.forEach($scope.allData, function(flidata) {
angular.forEach(flidata.flightsDepartur, function(flidatIn) {
console.log(flidatIn.fare);
});
});
}
Try change
angular.forEach(flidata[0].flightsDepartur, function(flidatIn) {..
to
angular.forEach(flidata.flightsDepartur, function(flidatIn) {..
and when using then function to get response change to this.
$http.get('data.json').then(function(response) {
$scope.allData = response.data;
},function(dataStatus){
console.log(dataStatus);
});
Demo
var app = angular.module('anApp', []);
app.controller('ctrl', function($scope) {
$scope.allData = [{
"flightsDepartur": [{
"fare": "9,000",
"route": [{
"source": "Delhi",
}],
}, ]
}]
angular.forEach($scope.allData, function(flidata) {
angular.forEach(flidata.flightsDepartur, function(flidatIn) {
console.log(flidatIn.fare);
console.log(flidatIn.route[0].source);
});
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
<div ng-app="anApp" ng-controller="ctrl">
</div>
While writing the above code in AngularJs, I am getting an error :
Error: $injector:unpr
Unknown Provider
Unknown provider: $http
I believe the reason might be while injecting $http through the serviceProvider which in my case is httpServiceProviderFunction.$inject = ["$http"];. I would appreciate if anyone could help me understand these two questions:
1) Although I have injected the $http in the httpServiceProviderFunction. Why am I getting the above error?
2)Is there any way I can inject $http in the service directly without injecting in serviceProvider? In my example, it corresponds to this line:
function httpService(url, $http) {.....}
The code snippet can be found below:
(function() {
angular.module("httpServiceApp", []).controller("httpServiceController", httpServiceControllerFunction).provider("httpService", httpServiceProviderFunction).config(configObj);
configObj.$inject = ["httpServiceProvider"]
function configObj(httpServiceProvider) {
httpServiceProvider.configuration.baseUrl = "http://davids-restaurant.herokuapp.com/categories.json";
}
httpServiceProviderFunction.$inject = ["$http"];
function httpServiceProviderFunction($http) {
var provider = this;
provider.configuration = {
baseUrl: "http://davids-restaurant.herokuapp.com/categories.json"
}
provider.$get = function() {
var service = new httpService(provider.configuration.baseUrl, $http);
return service;
}
}
function httpService(url, $http) {
var service = this;
service.menuCategories = function() {
var response = $http({
method: "GET",
url: url
});
return response;
}
}
httpServiceControllerFunction.$inject = ["httpService"]
function httpServiceControllerFunction(httpService) {
var service = httpService;
var controller = this;
var promise = service.menuCategories();
promise.then(function(response) {
controller.categories = response.data;
}).catch(function(error) {
console.log("Error occured", error);
})
}
})();
<!DOCTYPE html>
<html ng-app="httpServiceApp">
<head>
<meta charset="utf-8">
<meta name="description" content="First Angular App">
<meta name="keywords" content="HTML, Javascript, AngularJs">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.angularjs.org/1.6.1/angular.min.js"></script>
<script src="app1.js"></script>
<title>HTTP service in AngularJs</title>
</head>
<body>
<div ng-controller="httpServiceController as controller">
<div>
<ul>
<li ng-repeat="items in controller.categories">({{items.short_name}}){{items.name}}</li>
</ul>
</div>
</div>
</body>
</html>
Thank you for your time. I appreciate your help.
I am trying to connect WCF RESTful C# API to phonegap application using angularjs. My html working perfect in Web but no in my windows phone.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="myApp">
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Profile</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
</head>
<body>
<div>
<div data-ng-controller="ProfileCtrl">
First Name: {{FirstName}}
Last Name: {{LastName}}
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<!--<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>-->
<script type="text/javascript" src="js/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
window.jsoncallback = function (json) {
debugger;
if (!json.Error) {
alert("run callback");
//alert("success");
}
else {
alert(json.Message);
}
}
myApp.controller('ProfileCtrl', ["$scope", "$http", function ($scope, $http) {
function LoadProfile() {
debugger;
var call_url = 'http://localhost:53834/LoginService.svc/UserProfile/1';
//For jsonp calling
//alert("Running Jsonp");
//$http.jsonp(call_url).success(function (data) {
// debugger;
//});
alert("Running Ajax");
$.ajax({
url: call_url,
type: "POST",
dataType: "jsonp", // from the server
crossDomain: true,
contentType: "application/json; charset=utf-8", // to the server
jsonpCallback: 'jsoncallback',
success: function (data) {
alert("success");
$scope.FirstName = data.FirstName;
$scope.LastName = data.LastName;
$scope.$apply();
},
}).done(function (data) {
debugger;
console.log(data);
}).fail(function (xhr, status, error) {
debugger;
alert(xhr.status + " " + status + " " + error);
});
};
LoadProfile();
}]);
</script>
</body>
</html>
Here is my html code,
Service code is
public Stream UserProfile(string profileID)
{
TestDBEntities db = new TestDBEntities();
int _ProfileID = Convert.ToInt32(profileID);
tblProfile objtblProfile = db.tblProfiles.Find(_ProfileID);
string jsCode;
JavaScriptSerializer returnList = new JavaScriptSerializer();
string output = returnList.Serialize(objtblProfile);
if (objtblProfile != null)
jsCode = "jsoncallback" + "(" + output + ");";
else
jsCode = null;
WebOperationContext.Current.OutgoingResponse.ContentType = "application/javascript";
return new MemoryStream(Encoding.UTF8.GetBytes(jsCode));
}
I have done all things but not working in my windows phone it is giving an error
200 parserror: jsoncallback was not called
but it is working perfect in Web normally.
The way I made an AJAX request in my application is as below. Take a look and see if this works out for you:
app.ajaxCall = function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', <URL>, false);
//Content-Type can be based on the content you are sending
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var params = <define param string here>;
xhr.send(params);
var isError = false;
try {
if (xhr.status === 200) {
var jsonResponse = JSON.parse(xhr.responseText);
<logic>
}
};
Hope this helps.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="backbone.js"></script>
<script type="text/javascript" src="jquery-min1.4.js"></script>
<script>
//MODEL CREATION
var person=Backbone.Model.extend(
{
initialize: function()
{
alert("hello backbone");
}
});
function perf()
{
var val=new person();
}
</script>
</head>
<body>
<button onclick="perf()">CLICK</button>
</body>
</html>
This is a simple code, alert is not invoked in the model when an instance of it is created in the perf() function which is called while clicking the button... Please help
Try to write your code in $(function() {}); block or $(document).ready(function () {}); block.
It should work.
You are missing a script reference to Underscore.js
<script type="text/javascript" src="underscore.js"></script>
Backbone requires it as a dependency.
Download it at http://underscorejs.org/ then put it above your script element for backbone.js and it will work fine.
Here's jsfiddle that included both suggestions by dcarson & Naresh J , http://jsfiddle.net/Rvn2L/1/
$(function () {
var person = Backbone.Model.extend({
initialize: function () {
alert("hello backbone");
}
});
function perf() {
console.log('1');
var val = new person();
}
window.perf = perf;
})