Not reading the second data from json - json

I am trying to read data from json (2 cycles) and add an entry. the first time, the data added successfully but during the second cycle, it failed. below are the details. Also working when run with page object and without reading from json;
The "test_pom_fromjson" added successfully but when running for the test_pom_fromjson_first it failed with error saying no element found using element(by.id('s2id_autogen10')).click(); which is the locator for location column.
Refer the screenshot and html code for the page - https://pastebin.com/ZXyRx1tv
mo.ts: pageobject for the below spec file
var mo = function () {
this.createbutton = function () {
var createb = element(by.css('button[title="Add Master Obligation"]'))
//var createbutton = element(by.buttonText('↵ ↵ Add Master Obligatio...↵ '))
browser.executeScript("arguments[0].scrollIntoView();arguments[1].click();", createb, createb);
}
this.MasterObligationName = function (value) {
element(by.model('obligation.ObligationName')).sendKeys(value);
}
this.Module = function (value) {
element(by.id('s2id_TaxProcess')).click();
element.all(by.repeater('item in obligation.TaxProcess.list')).get(value).click();
}
this.Location = function (value) {
element(by.id('s2id_autogen10')).click();
element.all(by.repeater('item in obligation.Jurisdiction.list')).get(value).click();
}
this.CentralObligation = function (value) {
element.all(by.model('obligation.CentralObligation')).get(value).click();
}
this.Type = function (value) {
element(by.id('s2id_txtReturnType')).click();
element.all(by.repeater('item in obligation.ReturnType.list')).get(value).click();
}
this.Years = function (value) {
element(by.id('s2id_txtTaxYear')).click();
element.all(by.repeater('item in obligation.TaxYears.list')).get(value).click();
}
this.Periods = function (value) {
element(by.id('s2id_txtPeriod')).click();
element.all(by.repeater('tem in obligation.Periods.list')).get(value).click();
}
this.Forms = function (value) {
element.all(by.id('s2id_txtForms')).get(0).click();
element.all(by.repeater('item in obligation.Forms.list')).get(value).click();
}
this.Reports = function (value) {
element.all(by.id('s2id_txtForms')).get(1).click();
element.all(by.repeater('item in obligation.Reports.list')).get(value).click();
}
this.savebutton = function () {
var saveb = element(by.css('button[title="Save"]'))
browser.executeScript("arguments[0].scrollIntoView();arguments[1].click();", saveb, saveb);
}
module.exports = new mo();
spec.ts: var mo = require("../page/mo.ts")
var testData = require('../testdata/testdata.json');
testData.forEach(function (data) {
it('create and save master obligation', function () {
browser.sleep(10000);
mo.createbutton();
browser.sleep(10000);
mo.MasterObligationName(data.Master_Obligation_Name)
mo.Module(data.Module);
mo.Location(data.Location);
mo.CentralObligation(data.Central_Obligation);
mo.Type(data.Type);
mo.Years(data.Years);
mo.Periods(data.Periods);
mo.Forms(data.Forms);
mo.Reports(data.Reports);
mo.savebutton();
})
})
testdata.json:
[{
"Master_Obligation_Name": "test_pom_fromjson",
"Module": "2",
"Location": "1",
"Central_Obligation": "0",
"Type": "2",
"Years": "1",
"Periods": "1",
"Forms": "1",
"Reports": "0"
},
{
"Master_Obligation_Name": "test_pom_fromjson_first",
"Module": "2",
"Location": "1",
"Central_Obligation": "0",
"Type": "2",
"Years": "1",
"Periods": "1",
"Forms": "1",
"Reports": "0"
}]

Two options you can try:
1.Wait for some time before that click
2.Either id number is auto generated so it might be changed everytime, so use some other locator.
If the id is auto-generated then look for some other locator then:
element.all(by.id('s2id_Jurisdiction')).get(1).click();
element.all(by.repeater('item in obligation.Jurisdiction.list')).get(value).click();
OR you can also try the following way:
var module = element(by.xpath("//input[starts-with(#id, 's2id_autogen')]")).get(1).click();
var location= element(by.xpath("//input[starts-with(#id, 's2id_autogen')]")).get(2).click();
var type = element(by.xpath("//input[starts-with(#id, 's2id_autogen')]")).get(3).click();

Related

Import collection using button importing same collection multiple times - Postman

I'm using Postman version 6.6.0, and trying import API collection via Run in Postman button. I have one HTML page which looks like:
<div id="hiddenEnv" class="nodisplay highlight highlight-attention">
<p>
Click the button below to import into Postman
</p>
<p>
<div class="postman-run-button"
data-postman-action="collection/import"
data-postman-var-1="abcd"></div>
<script type="text/javascript">
(function (p,o,s,t,m,a,n) {
!p[s] && (p[s] = function () { (p[t] || (p[t] = [])).push(arguments); });
!o.getElementById(s+t) && o.getElementsByTagName("head")[0].appendChild((
(n = o.createElement("script")),
(n.id = s+t), (n.async = 1), (n.src = m), n
));
}(window, document, "_pm", "PostmanRunObject", "https://run.pstmn.io/button.js"));
</script>
</p>
</div>
And js code:
$(function() {
var lastEnv;
function newEnv(name) {
debugger;
var env = {
"id": generateUUID(),
"name": "MyProject-" + name,
"values": [{
"key": "hostenv",
"value": "",
"type": "text",
"enabled": true
},
{
"key": "username",
"value": "",
"type": "text",
"enabled": true
},
{
"key": "password",
"value": "",
"type": "text",
"enabled": true
}
],
"timestamp": 1544608923,
"synced": false,
"syncedFilename": "",
"team": null,
"isDeleted": false
};
return env;
}
$('#enter-creds').on('click', function(ev) {
var options = {
"name": "sampleBasicModal",
"content": $("script#envModal").html(),
onComplete: function(ev) {
console.log(ev);
var modal = $(ev.currentTarget).closest('.modal');
var form = modal.find('form');
console.log(form);
var formArr = form.serializeArray();
var envName = _.find(formArr, {name: 'hostenv'}).value.split('.')[0];
var envOutput = newEnv(envName);
var formObj = {};
formObj.hostenv = _.find(formArr, {name: 'hostenv'}).value;
formObj.username = _.find(formArr, {name: 'username'}).value;
formObj.password = _.find(formArr, {name: 'password'}).value;
if (!_pm('env.create', 'MyProject-' + envName, formObj)) {
_pm('env.replace', 'MyProject-' + envName, formObj);
}
lastEnv = envOutput;
$('#shownEnv').remove();
$('#hiddenEnv').slideDown(750);
}
};
var inst = Olive.modal.show(options);
ev.preventDefault();
});
});
I'm able to import my collections to Postman environment. However, same collection keep adding 7 to 8 times. I couldn't find where is the issue!
Edit:
I have checked it few times and then found that issue occurred when I have multiple environments.
After discussing this issue with a Postman team member, they found that there is an issue in the Postman with Windows OS, here is the reported link
Collection getting imported multiple times when using RiP button [Windows]

Use JSON data coming from WebApi in AngularJS application

I get some data from a WebApi, the answer (below the code to get the datas) is in JSON. But I can't access this result from angularJS. The datas look like :
{
"$id": "1",
"result": [
{
"$id": "2",
"name": "Français",
"code": "FR",
"id": 1
},
{
"$id": "3",
"name": "Néerlandais",
"code": "NL",
"id": 2
},
{
"$id": "4",
"name": "English",
"code": "EN",
"id": 3
}
]
}
But I get the error below when I try to display the result :
data.result is undefined
I get the data like this :
(function () {
angular.module('myApp')
.factory('dataService', ['$q', '$http', dataService]);
function dataService($q, $http) {
return {
initFormCustomer: initFormCustomer
};
function initFormCustomer() {
return $http({
method: 'GET',
url: 'http://localhost:123456/api/forminit/customer/',
headers: {
},
transformResponse: transformCustomer,
cache: true
})
.then(sendResponseData)
.catch(sendGetCustomerError)
}
function sendResponseData(response) {
return response.data;
}
function transformCustomer(data, headersGetter) {
var transformed = angular.fromJson(data.result);
console.log(data.result[0]);
return transformed;
}
function sendGetCustomerError(response) {
return $q.reject('Error retrieving customer(s). (HTTP status: ' + response.status + ')');
}
}
}());
The controller :
(function () {
angular.module('myApp')
.controller('customerController', ['$location', '$scope', 'dataService', CustomerController]);
function CustomerController($location, $scope, dataService) {
var vm = this;
vm.languages = dataService.initFormCustomer();
}
}());
I think the transform function gets a json string that you have to deserialize before using it as an object... try sth like:
function transformCustomer(data, headersGetter) {
var transformed = angular.fromJson(data);
console.log(transformed.result[0]);
return transformed.result;
}
Additionally you may look at the docs https://docs.angularjs.org/api/ng/service/$http . There is some code showing how to append a transform to the default one (that do the deserialization and XSRF checks)

Json response + Node.js

In my node app i pass bunch of queries as Object.I have to form as exact format of request.
Consider my request as:
{q0:{query0},q1:{query1},q2:{query1}}
My reponse should be {q0:{response0},q1{response1},q2{response2}
My actual query(In my app):
{"q0":{"query":"James Madison","type":"/people/presidents","type_strict":"should"},
"q1":{"query":"George Washington","type":"/people/presidents","type_strict":"should"},
"q2":{"query":"John Adams","type":"/people/presidents","type_strict":"should"},
"q3":{"query":"James Monroe","type":"/people/presidents","type_strict":"should"},
"q4":{"query":"Thomas Jefferson","type":"/people/presidents","type_strict":"should"}}
But my response is coming as:
{"result":[q0result,q1result,q3result]}
My code:
for (var id in presidents ) {
var match
if (query == presidents[id]) {
//console.log(" Inside match")
match = true;
}
else {
match = false;
}
matches.push({
"id": id,
//"name": name,
"score": 100,
"match": match,
"type": [{
"id": "/people/presidents",
"name": "US President"
}]
})
}
callback(matches);
json = JSON.stringify({"result":matches});
res.writeHead(200, {'content-type':'application/json'});
res.end(json);
Please help me to solve this..Thanks in advance.
You are pushing the result in an array instead you should create a property in the result object as below
var matches = {};
for (var id in presidents ) {
if (query == presidents[id]) {
//console.log(" Inside match")
match = true;
}
else {
match = false;
}
matches[id] ={
"id": id,
//"name": name,
"score": 100,
"match": match,
"type": [{
"id": "/people/presidents",
"name": "US President"
}]
};
}
callback(matches);

How to receive a json string after a jquery post in WebMatrix?

If I have the following post call:
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"uno": "lalala",
"dos": "jojojo"
}
var data = JSON.stringify(datos);
$.post(url, data, function (resultado) {
$('#posted_values').html(resultado);
});
});
How can I receive and process the json object in a cshtml file? I mean what I put in Decode call:
if (IsPost)
{
var json_object = Json.Decode(Request???);
}
Edited to complete the answer of #MikeBrind, to help others with the same problem.
Example of using decode for a more complex json object.
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumber": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
var data = JSON.stringify(datos);
$.post(url, {"person": data}, function (resultado) {
$('#posted_values').html(resultado);
});
});
Receiving and using:
#{
dynamic json_object;
if (IsPost)
{
json_object = Json.Decode(Request["person"]);
#json_object.firstName<br/>
#json_object.lastName<br/>
#json_object.address.city<br/>
#json_object.address.postalCode<br/>
foreach (dynamic phone in json_object.phoneNumber)
{
#phone.type<br/>
#phone.number
}
}
}
Don't JSON.stringify the data if it is just key/value pairs like this. Do a form post:
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"uno": "lalala",
"dos": "jojojo"
}
//var data = JSON.stringify(datos); no need for this
$.post(url, datos, function (resultado) {
$('#posted_values').html(resultado);
});
});
Then the values are available from Request["uno"] and Request["dos"]
If you ever do need to use JSON.stringify (which you would for more complex data structures), the JSON is transmitted in the Request body, so you need to extract it from Request.InputStream:
var reader = new StreamReader(Request.InputStream);
var json = reader.ReadToEnd();

Passing Json from action to view by ViewBag

I'm trying to get the result below using JsonResult, but I can't
var localJSON = [
{ "id": "1", "label": "tagName1", "value": "tagValue1" },
{ "id": "2", "label": "tagName2", "value": "tagValue2" },
{ "id": "3", "label": "tagName3", "value": "tagValue3" },
{ "id": "1553", "label": "tagName1553", "value": "tagValue1553" }
];
Here is the way I use:
controller
private JsonResult GetAvailableTags()
{
var tagsList = Facade.Tags.Get(CurrentLocale.ID);
var retValue = new
{
id = tagsList.Select(x => x.ID).ToArray(),
label = tagsList.Select(x => x.Name).ToArray(),
value = tagsList.Select(x => x.Name).ToArray()
};
return Json(retValue);
}
public ActionResult AddPhoto()
{
var availblableTags = GetAvailableTags();
JavaScriptSerializer serializer = new JavaScriptSerializer();
ViewBag.AvailableTags = serializer.Serialize(availblableTags.Data);
return View();
}
view
var localJSON = [ #Html.Raw(ViewBag.AvailableTags)];
The result is
var localJSON = [
{"id":[1,2,3,1553],"label":["tagName1","tagName2","tagName3","tagName1553" ],"value":["tagName1","tagName2","tagName3","tagName1553" ]}
];
What should I do to resolve that?
I assume you want to get x.Value for value in JSON? Then change your assignment for retValue to
var retValue = tagsList.Select(
x => new
{
id = x.Id,
label = x.Name,
value = x.Value
}).ToArray();
In your retValue assignment code you were creating a single object of anonymous type with array-typed members id, label and value. For the output you want you need to create an array, each member of which is an object with simple fields id, name and value.