How to use brower.get() in protractor - javascript

I was using Protractor to test dropdown selection. The code is following:
var productCountry = element(by.model('main.productCountry1'));
productCountry.click();
var country = element.all(by.repeater('country in countries'));
country.get(5).click();
browser.sleep(500);
The error is:
Stack:
ElementNotVisibleError: element not visible
(Session info: chrome=44.0.2403.81)`
I used code to see the data inside array [names]:
var names =element.all(by.repeater('country in countries').column('country.name'));
names.getText().then(function(txt){
console.log(txt);
});
And the result shows the array looks like this:
['','', '', '', '', .....,'','Kenya','Kiribati',....,'','','','']
Only can get a part of elements, other elements are all empty. And I run several times,each time the empty parts are different.
I used the first line code
browser.get('dist/#');
browser.get('app/index.html');
to get into the webpage. If I run the above second line code, there is a 'Not Found' shown on the website,and the error is:
Stack:
Error: Failed: Error while running testForAngular: asynchronous script timeout: result was not received in 11 seconds
(Session info: chrome=44.0.2403.81)
Does this caused the element empty? The example I saw online always used the second line browser.get(). Is there any one used the first method?
I found If changed the data in $scope.country in scr/app/tab/main.controller, when I run gulp serve, the options in selection changed, but when I run protractor and get from the dist/#, the options are not changed. I guess it maybe caused the element empty. And I used yeoman to generate the files.

For the bower.get():
I used the code like this "browser.get ('/'); " to instead of the two lines of code shown in the question. It will now show the index page.
For drop-down selection test:
There are two things causing this error.
var productCountry = element(by.id('countryName'));
var country1 = element.all(by.repeater('country1 in countries'));
productCountry.click();
browser.sleep(500);
var a = country1.get(2);
a.click();
browser.sleep(500);
expect(a.getAttribute('value')).toEqual('Indonesia');
Here is my code. One reason is after doing productCountry.click(), we need to let the browser sleep for a while to wait for the renderings to take effect.
The other reason is I used two of the same repeater in my HTML file, and when I do the e2e test, the system can't distinguish which repeater I want attached to the element. So I changed the code from:
var names =element.all(by.repeater('country in countries').column('country.name'));
to
var country1 = element.all(by.repeater('country1 in countries'));
var country2 = element.all(by.repeater('country2 in countries'));
And finally I can test two drop-down selections.

Related

Showing single data field via Google Analytics API

I'm having trouble displaying only a single data field via the Google Analytics API.
For example, how would I display the number of users yesterday? Or the number of users in the past week?
I'm assuming "gapi.analytics.report.Data" is the right constructor. I've tried following the "Data" code in Google's Built-in Components Reference but nothing displays on the front-end.
For the "DataChart" code, there's a "container" option that references the HTML element in the DOM that will correctly display the chart.
This "container" option is missing in "Data" - so how do I display a single data field?
EDIT: Here's the code I'm working with.
You can see a pastebin of my code here: https://pastebin.com/M6U0Bd8B
There's also a live staging version of the site here: http://madebychris.ca/dashboard2.html
The first four section ids are all displaying properly but nothing's showing up for the final <p class ="report">
If you are trying to access the raw data numbers, you can just access the response object:
// Set up the request
var report = new gapi.analytics.report.Data({
query: {
ids: 'ga:XXXX',
metrics: 'ga:sessions',
dimensions: 'ga:city'
}
});
// Define what to do with the response data.
report.on('success', function(response) {
console.log(response);
});
// Run the report
report.execute();
For example, the total's for the metrics is response.totalsForAllResults and the rows for each dimension are held in response.rows
You need to select what you want to do with the variables on the report.on("success", function(response){ function. For example:
report.on('success', function(response) {
$("body > main > div > section:nth-child(4) > h2")[0].innerText =
response.totalsForAllResults["ga:sessions"]
});
report.execute();
Note: You should be able to test on the embedded API demo. Copying and pasting the initial code with the console.log should help show what is going on.

refactor capybara javascript dropzone test

I'm trying to call a dropzone capybara test multiple times. However, when I call it a second time, the ID has already been used. I'm trying to randomize the ID so it can run multiple times.
def drop_in_dropzone(file_path)
page.execute_script <<-JS
fakeFileInput = window.$('<input/>').attr(
{id: 'fakeFileInput', type:'file'}
).appendTo('body');
JS
attach_file("fakeFileInput", file_path)
page.execute_script("var fileList = [fakeFileInput.get(0).files[0]]")
page.execute_script <<-JS
var e = jQuery.Event('drop', { dataTransfer : { files : [fakeFileInput.get(0).files[0]] } });
$('.dropzone')[0].dropzone.listeners[0].events.drop(e);
JS
end
Error when calling it 2nd time.
Failure/Error: attach_file("fakeFileInput", file_path)
Capybara::Ambiguous:
Ambiguous match, found 2 elements matching file field "fakeFileInput"
You can definitely just generate a random id number for the input but it might be easier to just only create the fakeFileInput it if doesn't already exist. This would only work if you don't use the input for any other purposes than in this method, but it seems like that's what you're doing.
page.execute_script <<-JS
fakeFileInput = fakeFileInput || window.$('<input/>').attr(
{id: '#{fake_input_id}', type:'file'}
).appendTo('body');
JS
If it did already exist it wouldn't get created again and it would just get reused.

Return arrays from meteor mongo

ajduke:bootstrap-tagsinput
I am using the above package to create a tags system. I have used <select multiple> from the True Input Value from the link above and have inserted each tags as Strings within the tag array.
This is what my db looks like.
Posts
tags //Array
[0] : sometag //String
[1] : sometag //String
[2] : sometag //String
//and so forth..
So my question is...
I want to return all the tags within a post to the following format, so that I can reuse it to show the tags when my users try to edit their posts.
Wanted Format
['sometag', 'sometag', 'sometag', and so forth]
Edit1
this is what I've done so far.
Post_Edit.js
Template.postEdit.rendered = function() {
myTags = Posts.findOne({_id: this._id}).tags.fetch(); //AAA
$('.tagsinput').tagsinput('add', myTags); //From above link API
}
I've tried other methods for //AAA line but I am having no luck.I've tried things such as Posts.findOne.map... Maybe my english comprehension is not up to par but the documentations in meteor did not help me understand any better.
Edit 2
Posts.findOne({_id: "ziZw3wLaxFyz3DYP4"}).tags
I've tried putting this in the browser console and got the array in the format that I wanted.
But the problem is, it won't work in my app when I use it.
When I use Posts.findOne({_id: this._id}).tags in my postEdit.rendered, I get this browser console error. Cannot read property 'tags' of undefined
Post_Edit.js
Template.postEdit.rendered = function() {
myTags = Posts.findOne({_id: this._id}).tags;
$('.tagsinput').tagsinput('add', myTags); //From above link API
}
What I don't understand is why is it working in browser console but not my Template.postEdit.rendered?
You are correct that your variable myTags is undefined when Template.postEdit.rendered is called because the Posts database has not finished loading when your function is called.
myTags = Posts.findOne({_id: this._id}).tags.fetch(); //AAA
Solution
There are multiple strategies including:
Updating DOM after subscription completes
http://docs.meteor.com/#/full/Blaze-TemplateInstance-subscribe
Re-run the function when Collection changes
http://docs.meteor.com/#/full/tracker_autorun
Template.postEdit.rendered = function() {
Tracker.autorun(function () { ** NEW LINE **
myTags = Posts.findOne({_id: this._id}).tags;
$('.tagsinput').tagsinput('add', myTags);
} ** NEW LINE **
}
I've approached a completely different way to figure this out.
But I'd still like to know why my method did not work...
post_edit.js
Template.postEdit.helpers({
tags: function(){
Posts.findOne({_id:this._id}).tags;
}
});
post_edit.html
<select class=tagsinput id="tagsinput" data-role="tagsinput">
{{#each}}
<option value="{{this}}">{{this}}</option>
{{/each}}

Restore multiple selections from db using Rangy

What i want to do :
->Show a plain HTML page to a user
->User has the ability to highlight text on that page
->When user logs in next time , i should be able to retrieve and show his previous (multiple) highlight on the page.
What i have done :
I used the Library/API : Rangy.With this iam able to select the text and highlight it with the users preferred color.
The Problem :
I tried the serialize and de-serialize function , but when i try to deserialize (after page has been reloaded) it gives me an error saying
checksums of serialized range root node (ec0c8cf0) and target root
node (d4997863) do not match
Everytime i reload the page , there is a new root node , how can i fix the deserialize in this case ?
Created a JS-Fiddle : demo / js-fiddle
What is this - If you check my demo , i select the first word of the description ie "Please " , i get the text highlighted , and i also get the serial as :
0/3/1/3/0/1/1/2:9,0/3/1/3/0/1/1/2:9{b3002d92}
so what i did is , i hard coded this serial and put it into the deserializeSelection funciton in the page onLoad function like this :-
rangy.deserializeSelection('0/3/1/3/0/1/1/2:9,0/3/1/3/0/1/1/2:9{b3002d92}');
so technically , it should highlight the "Please" in the description , whenever the page loads , irrespectively.But it does not , instead give me the above error in block.
Can you help me solve this.please.Thank you
Extra:
1.I really do not understand the serialize and de-serialize methods of rangy.
2.My very abstract road map from here is to , do an AJAX call , on page load and fetch all (serialized) selection of the user for this page from my db and iterate over them and do a de-serialize.
Any help , would be really appreciated.
Thank you.
What I think is you should try this:
var selObj = rangy.getSelection();
var se = rangy.serializeSelection(selObj, true); //true to avoid DOM checksum

webOS/Ares : read JSON from URL, assign to label

I've used the webOS Ares tool to create a relatively simple App. It displays an image and underneath the image are two labels. One is static, and the other label should be updated with new information by tapping the image.
When I tap the image, I wish to obtain a JSON object via a URL (http://jonathanstark.com/card/api/latest). The typcial JSON that is returned looks like this:
{"balance":{"amount":"0","amount_formatted":"$0.00","balance_id":"28087","created_at":"2011-08-09T12:17:02-0700","message":"My balance is $0.00 as of Aug 9th at 3:17pm EDT (America\/New_York)"}}
I want to parse the JSON's "amount_formatted" field and assign the result to the dynamic label (called cardBalance in main-chrome.js). I know that the JSON should return a single object, per the API.
If that goes well, I will create an additional label and convert/assign the "created_at" field to an additional label, but I want to walk before I run.
I'm having some trouble using AJAX to get the JSON, parse the JSON, and assign a string to one of the labels.
After I get this working, I plan to see if I can load this result on the application's load instead of first requiring the user to tap.
So far, this is my code in the main-assistant.js file. jCard is the image.
Code:
function MainAssistant(argFromPusher) {}
MainAssistant.prototype = {
setup: function() {
Ares.setupSceneAssistant(this);
},
cleanup: function() {
Ares.cleanupSceneAssistant(this);
},
giveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
},
jcardImageTap: function(inSender, event) {
//get "amount_formatted" in JSON from http://jonathanstark.com/card/api/latest
//and assign it to the "updatedBalance" label.
// I need to use Ajax.Request here.
Mojo.Log.info("Requesting latest card balance from Jonathan's Card");
var balanceRequest = new Ajax.Request("http://jonathanstark.com/card/api/latest", {
method: 'get',
evalJSON: 'false',
onSuccess: this.balanceRequestSuccess.bind(this),
onFailure: this.balanceRequestFailure.bind(this)
});
//After I can get the balance working, also get "created_at", parse it, and reformat it in the local time prefs.
},
//Test
balanceRequestSuccess: function(balanceResponse) {
//Chrome says that the page is returning X-JSON.
balanceJSON = balanceResponse.headerJSON;
var balanceAmtFromWeb = balanceJSON.getElementsByTagName("amount_formatted");
Mojo.Log.info(balanceAmtFromWeb[0]);
//The label I wish to update is named "updatedBalance" in main-chrome.js
updatedBalance.label = balanceAmtFromWeb[0];
},
balanceRequestFailure: function(balanceResponse) {
Mojo.Log.info("Failed to get the card balance: " + balanceResponse.getAllHeaders());
Mojo.Log.info(balanceResponse.responseText);
Mojo.Controller.errorDialog("Failed to load the latest card balance.");
},
//End test
btnGiveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
}
};
Here is a screenshot of the application running in the Chrome browser:
In the browser, I get some additional errors that weren't present in the Ares log viewer:
XMLHttpRequest cannot load http://jonathanstark.com/card/api/latest. Origin https://ares.palm.com is not allowed by Access-Control-Allow-Origin.
and
Refused to get unsafe header "X-JSON"
Any assistance is appreciated.
Ajax is the right tool for the job. Since webOS comes packaged with the Prototype library, try using it's Ajax.Request function to do the job. To see some examples of it, you can check out the source code to a webOS app I wrote, Plogger, that accesses Blogger on webOS using Ajax calls. In particular, the source for my post-list-assistant is probably the cleanest to look at to get the idea.
Ajax is pretty much the way you want to get data, even if it sometimes feels like overkill, since it's one of the few ways you can get asynchronous behavior in JavaScript. Otherwise you'd end up with code that hangs the interface while waiting on a response from a server (JavaScript is single threaded).

Categories

Resources