How to return window.performance object to CasperJS scope - coffeescript

I'm trying to return window.performance object from the web page back to casper's scope with the following code but I'm getting null. Can someone explain why?
performance = casper.evaluate ->
return window.performance
#echo performance

PhantomJS 1.x doesn't implement window.performance, so you can't use it.
PhantomJS 2.0.0 implements it, but it doesn't implement the window.performance.toJSON() function. The problem with PhantomJS is that you have to access this information through evaluate(), but it has the following limitation:
Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.
Closures, functions, DOM nodes, etc. will not work!
You will have to find your own way of serializing this in the page context and passing it to the outside (JavaScript):
var performance = casper.evaluate(function(){
var t = window.performance.timing;
var n = window.performance.navigation;
return {
timing: {
connectStart: t.connectStart,
connectEnd: t.connectEnd,
...
},
navigation: {
type: n.type,
redirectCount: n.redirectCount
},
...
};
});
or look for a deep copy algorithm that produces a serializable object (from here):
var perf = casper.evaluate(function(){
function cloneObject(obj) {
var clone = {};
for(var i in obj) {
if(typeof(obj[i])=="object" && obj[i] != null)
clone[i] = cloneObject(obj[i]);
else
clone[i] = obj[i];
}
return clone;
}
return cloneObject(window.performance);
});
console.log(JSON.stringify(perf, undefined, 4));

Related

How to call script include from the client script service-now without GlideAjax

The common process we follow today to get the data on client script:
OnChange client script:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var user = g_form.getValue('u_user');
//Call script include
var ga = new GlideAjax('global.sampleUtils'); //Scriptinclude
ga.addParam('sysparm_name', 'getUserDetails'); //Method
ga.addParam('userId',user); //Parameters
ga.getXMLAnswer(getResponse);
function getResponse(response){
console.log(response);
var res = JSON.parse(response);
console.log(res);
g_form.setValue('u_phone',res.mobile_phone);
g_form.setValue('u_email',res.email);
}
}
Script include:
var sampleUtils = Class.create();
sampleUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getUserDetails: function(){ //Function
var userId = this.getParameter('userId'); //Params
obj = {};
var grSysUser = new GlideRecord('sys_user');
if (grSysUser.get(userId)) {
obj.mobile_phone = grSysUser.getValue('mobile_phone');
obj.email = grSysUser.getValue('email');
}
gs.addInfoMessage(obj+JSON.stringify(obj));
return JSON.stringify(obj);
},
type: 'sampleUtils'
});
DEMO Link: https://youtu.be/nNUsfglmj_M
As an alternative to glideAjax you can EfficientGlideRecord
new EfficientGlideRecord('sys_user')
.addQuery('sys_id', newValue) //On Change client script, we will get sys_id of user in newValue variable
.addField('mobile_phone', true) //Get display value
.query(function (egrSysUser) {
if(egrSysUser.next()) {
g_form.setValue('phone', egrSysUser.getDisplayValue('mobile_phone'));
}
});
What is EfficientGlideRecord?
EfficientGlideRecord is the best alternate way to use GlideAjax.
It is a client-side API class from which you can perform asynchronous client-side GlideRecord-style queries while maximizing performance.
Benefits:
Low code configuration with Huge performance improvement.
No need to worry about security loopholes, because it enforces ACLs.
No more concerns about creating new client callable script includes and maintaining
the logic there.
Dependencies:
To use the EfficientGlideRecord we need to commit the attached update-set or find the latest version from the given link https://github.com/thisnameissoclever/ServiceNow-EfficientGlideRecord/releases.
Add the package to Portal record -> JS Includes.
and that's it, and you are good at using the EfficientGlideRecord syntax.
To know more about EfficientGlideRecord, Refer the below link(s):
https://snprotips.com/efficientgliderecord

What's the correct Protractor's syntax for Page Objects?

I've come across different types of syntax for Protractor's Page Objects and I was wondering, what's their background and which way is suggested.
This is the official PageObject syntax from Protractor's tutorial. I like it the most, because it's clear and readable:
use strict;
var AngularHomepage = function() {
var nameInput = element(by.model('yourName'));
var greeting = element(by.binding('yourName'));
this.get = function() {
browser.get('http://www.angularjs.org');
};
this.setName = function(name) {
nameInput.sendKeys(name);
};
this.getGreeting = function() {
return greeting.getText();
};
};
module.exports = AngularHomepage;
However, I've also found this kind:
'use strict';
var AngularPage = function () {
browser.get('http://www.angularjs.org');
};
AngularPage.prototype = Object.create({}, {
todoText: { get: function () { return element(by.model('todoText')); }},
addButton: { get: function () { return element(by.css('[value="add"]')); }},
yourName: { get: function () { return element(by.model('yourName')); }},
greeting: { get: function () { return element(by.binding('yourName')).getText(); }},
todoList: { get: function () { return element.all(by.repeater('todo in todos')); }},
typeName: { value: function (keys) { return this.yourName.sendKeys(keys); }} ,
todoAt: { value: function (idx) { return this.todoList.get(idx).getText(); }},
addTodo: { value: function (todo) {
this.todoText.sendKeys(todo);
this.addButton.click();
}}
});
module.exports = AngularPage;
What are the pros/cons of those two approaches (apart from readability)? Is the second one up-to-date? I've seen that WebdriverIO uses that format.
I've also heard from one guy on Gitter that the first entry is inefficient. Can someone explain to me why?
Page Object Model framework becomes popular mainly because of:
Less code duplicate
Easy to maintain for long
High readability
So, generally we develop test framework(pom) for our convenience based on testing scope and needs by following suitable framework(pom) patterns. There are NO such rules which says that, strictly we should follow any framework.
NOTE: Framework is, to make our task easy, result oriented and effective
In your case, 1st one looks good and easy. And it does not leads to confusion or conflict while in maintenance phase of it.
Example: 1st case-> element locator's declaration happens at top of each page. It would be easy to change in case any element locator changed in future.
Whereas in 2nd case, locators declared in block level(scatter across the page). It would be a time taking process to identify and change the locators if required in future.
So, Choose which one you feel comfortable based on above points.
I prefer to use ES6 class syntax (http://es6-features.org/#ClassDefinition). Here, i prepared some simple example how i work with page objects using ES6 classes and some helpful tricks.
var Page = require('../Page')
var Fragment = require('../Fragment')
class LoginPage extends Page {
constructor() {
super('/login');
this.emailField = $('input.email');
this.passwordField = $('input.password');
this.submitButton = $('button.login');
this.restorePasswordButton = $('button.restore');
}
login(username, password) {
this.email.sendKeys(username);
this.passwordField.sendKeys(password);
this.submit.click();
}
restorePassword(email) {
this.restorePasswordButton.click();
new RestorePasswordModalWindow().submitEmail(email);
}
}
class RestorePasswordModalWindow extends Fragment {
constructor() {
//Passing element that will be used as this.fragment;
super($('div.modal'));
}
submitEmail(email) {
//This how you can use methods from super class, just example - it is not perfect.
this.waitUntilAppear(2000, 'Popup should appear before manipulating');
//I love to use fragments, because they provides small and reusable parts of page.
this.fragment.$('input.email').sendKeys(email);
this.fragment.$('button.submit')click();
this.waitUntilDisappear(2000, 'Popup should disappear before manipulating');
}
}
module.exports = LoginPage;
// Page.js
class Page {
constructor(url){
//this will be part of page to add to base URL.
this.url = url;
}
open() {
//getting baseURL from params object in config.
browser.get(browser.params.baseURL + this.url);
return this; // this will allow chaining methods.
}
}
module.exports = Page;
// Fragment.js
class Fragment {
constructor(fragment) {
this.fragment = fragment;
}
//Example of some general methods for all fragments. Notice that default method parameters will work only in node.js 6.x
waitUntilAppear(timeout=5000, message) {
browser.wait(this.EC.visibilityOf(this.fragment), timeout, message);
}
waitUntilDisappear(timeout=5000, message) {
browser.wait(this.EC.invisibilityOf(this.fragment), timeout, message);
}
}
module.exports = Fragment;
// Then in your test:
let loginPage = new LoginPage().open(); //chaining in action - getting LoginPage instance in return.
loginPage.restorePassword('batman#gmail.com'); // all logic is hidden in Fragment object
loginPage.login('superman#gmail.com')

How can I leverage reactive extensions to do caching, without a subject?

I want to be able to fetch data from an external Api for a specific request, but when that data is returned, also make it available in the cache, to represent the current state of the application.
This solution seems to work:
var Rx = require('rx');
var cached_todos = new Rx.ReplaySubject(1);
var api = {
refresh_and_get_todos: function() {
var fetch_todos = Rx.Observable.fromCallback($.get('example.com/todos'));
return fetch_todos()
.tap(todos => cached_todos.onNext(todos));
},
current_todos: function() {
return cached_todos;
}
};
But - apparently Subjects are bad practice in Rx, since they don't really follow functional reactive programming.
What is the right way to do this in a functional reactive programming way?
It is recommended not to use Subjects because there is a tendency to abuse them to inject side-effects as you have done. They are perfectly valid to use as ways of pushing values into a stream, however their scope should be tightly constrained to avoid bleeding state into other areas of code.
Here is the first refactoring, notice that you can create the source beforehand and then your api code is just wrapping it up in a neat little bow:
var api = (function() {
var fetch_todos = Rx.Observable.fromCallback($.get('example.com/todos'))
source = new Rx.Subject(),
cached_todos = source
.flatMapLatest(function() {
return fetch_todos();
})
.replay(null, 1)
.refCount();
return {
refresh: function() {
source.onNext(null);
},
current_todos: function() {
return cached_todos;
}
};
})();
The above is alright, it maintains your current interface and side-effects and state have been contained, but we can do better than that. We can create either an extension method or a static method that accepts an Observable. We can then simplify even further to something along the lines of:
//Executes the function and caches the last result every time source emits
Rx.Observable.withCache = function(fn, count) {
return this.flatMapLatest(function() {
return fn();
})
.replay(null, count || 1)
.refCount();
};
//Later we would use it like so:
var todos = Rx.Observable.fromEvent(/*Button click or whatever*/))
.withCache(
Rx.Observable.fromCallback($.get('example.com/todos')),
1 /*Cache size*/);
todos.subscribe(/*Update state*/);

Backbone Send Post data encoded as query string

I'm creating a backbone app that's connecting to a RESTful backend. When I call save() on a model, it sends the post data as stringified JSON:
{"firstName":"first","lastName":"last","Email":"email#gmail.com"}
but my server expects it to be formatted like a querystring:
firstName=first&lastName=last&Email=email#gmail.com
is there a way to have backbone send it differently?
Backbone doesn't provide anything like this out of the box.
But is easy to override and customize it to your needs.
Have a look to the source code:
http://documentcloud.github.com/backbone/docs/backbone.html
and check out that calling save, it will trigger a sync call in the background.
So what you need is to override Backbone.sync function with your own.
I would modify the part of:
if (!options.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
with
if (!options.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = $.param(model); // <-- CHANGED
}
Notice I'm using jQuery param
If you want to use a custom function, check this question:
Query-string encoding of a Javascript Object
[Update.]
No need to modify directly. Better override it with your own function 'Backbone.sync'
Check the "TODO" example of the Backbone repository. It has a localStorage.js file that overrides Backbone.sync function https://github.com/documentcloud/backbone/tree/master/examples
I ran into this problem at work and the Backbone.emulateJSON didn't work for me either. With some help I was able to come up with this workaround. We overrode the Backbone.ajax function and changed the contentType to "application/x-www-form-urlencoded" and used $.param to properly serialize the data.
Backbone.ajax = function() {
if(arguments[0].data && arguments[0].contentType == "application/json"){
arguments[0].data = $.param(JSON.parse(arguments[0].data));
arguments[0].contentType = "application/x-www-form-urlencoded";
}
return Backbone.$.ajax.apply(Backbone.$, arguments);
}
maybe this can help you,try:
http://backbonejs.org/#Sync-emulateJSON
I have done this by overriding model's sync function:
var MyModel = Backbone.Model.extend({
"sync": function(method, model, options) {
if (method == "update" || method == "create") {
options = options ? _.clone(options) : {};
options['data'] = $.param(this['attributes']);
}
var arguments = [method, model, options];
return Backbone.sync.apply(this, arguments);
}
});
I find solutions, see :
I use
Backbone.emulateJSON = true;
I write the "update" case:
options.url = "/user/"+Math.random(1, 1000);
options.type = "POST";
//.1/2 WORK
//options.data = (model instanceof Backbone.Model)?model.toJSON():{};
options.data = model.toJSON();
break;
Backbone.sync uses the jQuery.ajax function, so we can modify the jqXHR or data that is sended to the server (via beforeSend).
var oldSync = Backbone.Model.prototype.sync;
var SomeModel = Backbone.Model.extend({
url: 'test.json',
defaults: {
id: 1,
foo: 'test'
},
sync: function (method, model, options) {
// options are passed to the jQuery.ajax
_.extend(options, {
emulateHTTP: true,
emulateJSON: false,
beforeSend: function(xhr, settings) {
// settings.data is a body of our request.
if (_.isString(settings.data)) {
// settings.data is a JSON-string like '{"id":1, "foo":"test"}'
settings.data = Backbone.$.parseJSON(settings.data);
}
settings.data = Backbone.$.param(settings.data);
// settings.data is 'id=1&foo=test'
}
});
oldSync.apply(this, arguments);
}
});
var model = new SomeModel();
model.save();
Actually we can create a mixin! :)

Error destroying Backbone Relational model generated with Coffeescript

I have a situation which has to be simple to solve, I would guess. Surely people are using Backbone Relational with CoffeeScript out there...
Here's a model I have:
class MyCompany.Models.Establishment extends Backbone.RelationalModel
defaults:
name: null
class MyCompany.Collections.EstablishmentsCollection extends Backbone.Collection
model: MyCompany.Models.Establishment
url: '/establishments'
I haven't even added any relationships yet, just extended RelationalModel. Now through the console when I issue a destroy on an instance of the model it successfully destroys the model on the server, but when complete it fails with the trace:
Uncaught TypeError: Object #<Establishment> has no method 'getCollection'
_.extend.unregister
Backbone.Events.trigger
Backbone.RelationalModel.Backbone.Model.extend.trigger
_.extend.destroy.options.success
jQuery.extend._Deferred.deferred.resolveWith
done
jQuery.ajaxTransport.send.callback
It's dying in line 235 of backbone-relational.js 0.4.0 because "this" is the model, I guess, instead of whatever it's supposed to be, and the model doesn't have a method "getCollection".
Any ideas what I'm doing wrong, or should I report a bug? For reference, here's the Javascript coffee generates:
(function() {
var __hasProp = Object.prototype.hasOwnProperty, __extends = function(child, parent) {
for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; }
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.__super__ = parent.prototype;
return child;
};
MyCompany.Models.Establishment = (function() {
__extends(Establishment, Backbone.RelationalModel);
function Establishment() {
Establishment.__super__.constructor.apply(this, arguments);
}
Establishment.prototype.defaults = {
name: null
};
return Establishment;
})();
MyCompany.Collections.EstablishmentsCollection = (function() {
__extends(EstablishmentsCollection, Backbone.Collection);
function EstablishmentsCollection() {
EstablishmentsCollection.__super__.constructor.apply(this, arguments);
}
EstablishmentsCollection.prototype.model = MyCompany.Models.Establishment;
EstablishmentsCollection.prototype.url = '/establishments';
return EstablishmentsCollection;
})();
}).call(this);
You need to update the underlying Backbone.js version. Here's why:
Your error comes from this having the wrong value when unregister is called. unregister is called in response to an event bound from register:
model.bind( 'destroy', this.unregister, this );
That third argument sets the context. But that feature was only added as recently as Backbone 0.5.2, as the changelog shows.