SlimerJS is not running my script - javascript

I am trying to run my CasperJS test using slimerJS, and it just do nothing, opened the FF browser and displayed the SlimerJS logo. If I am trying to run a simple script like loading of Google homepage or something it works fine. Attached the script below, can you please tell me what is wrong there? Thanks!
// Simple messaging flow
action_helpers_v2 = require('../v2_modules/action_helpers_v2.js');
helpers_v2 = require('../v2_modules/helpers_v2.js');
var staging = casper.cli.get('staging'),
unixTimeStamp = (Date.now()).toString().substring(4),
currentTime = new Date(),
currentHour = currentTime.getHours(),
timeout = 15000;
var genereateText = function genereateText() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 20; i++ ) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
var mouse = require("mouse").create(casper);
var webPage = require('webpage');
var page = webPage.create();
var live = casper.cli.get("prod"),
staging = casper.cli.get("staging"),
localeTesting = casper.cli.get("localeTesting"),
buyerUserName = 'settings120',
buyerPassword = 123456,
orders_array = [],
numberOfTests = 0;
casper.test.begin("Test Name: simple messaging flow", function suite(test) {
casper.start('http://fiverr.com');
casper.then(function() {
if (staging) {
action_helpers_v2.enableStaging(staging);
}
});
casper.then(function() {
action_helpers_v2.navigateToHomepage();
});
casper.then(function() {
action_helpers_v2.login(buyerUserName,buyerPassword);
action_helpers_v2.navigateToConversation("yogev_a");
});
casper.wait(5000);
var message = genereateText();
casper.then(function() {
casper.evaluate(function(message) {
$('#message_body')[0].value = message;
}, message);
});
casper.then(function() {
casper.evaluate(function() {
$('.btn-send-message')[0].click()
});
});
casper.waitForText(message, function() {
casper.test.pass("Message was sent");
}, function() {
helpers_v2.printScreenAndMessage('message_error', 'message_error');
casper.test.fail("Message wasnt sent");
});
casper.run(function(){
test.done();
});
});

Related

What is wrong with my JS webassemblity player?

I am trying to port a C++ program to WASM using emscripten.
The compilation process has been mastered, but so far with the presentation, which is bad ... I have
problem:
Uncaught ReferenceError: request is not defined
request.onload = function() {
Here is my script:
<script type='text/javascript'>
request.onload = function() {
var bytes = request.response;
fetch('hello.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, importObject)
).then(results => {
// Do something with the results!
console.log(results);
});
};
var statusElement = document.getElementById('status');
var progressElement = document.getElementById('progress');
var spinnerElement = document.getElementById('spinner');
var Module = {
preRun: [],
postRun: [],
print: (function() {
var element = document.getElementById('output');
if (element) element.value = ''; // clear browser cache
return function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
// These replacements are necessary if you render to raw HTML
//text = text.replace(/&/g, "&");
//text = text.replace(/</g, "<");
//text = text.replace(/>/g, ">");
//text = text.replace('\n', '<br>', 'g');
console.log(text);
if (element) {
element.value += text + "\n";
element.scrollTop = element.scrollHeight; // focus on bottom
}
};
})(),
canvas: (function() {
var canvas = document.getElementById('canvas');
// As a default initial behavior, pop up an alert when webgl context is lost. To make your
// application robust, you may want to override this behavior before shipping!
// See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2
canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false);
return canvas;
})(),
setStatus: function(text) {
if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' };
if (text === Module.setStatus.last.text) return;
var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
var now = Date.now();
if (m && now - Module.setStatus.last.time < 30) return; // if this is a progress update, skip it if too soon
Module.setStatus.last.time = now;
Module.setStatus.last.text = text;
if (m) {
text = m[1];
progressElement.value = parseInt(m[2])*100;
progressElement.max = parseInt(m[4])*100;
progressElement.hidden = false;
spinnerElement.hidden = false;
} else {
progressElement.value = null;
progressElement.max = null;
progressElement.hidden = true;
if (!text) spinnerElement.style.display = 'none';
}
statusElement.innerHTML = text;
},
totalDependencies: 0,
monitorRunDependencies: function(left) {
this.totalDependencies = Math.max(this.totalDependencies, left);
Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.');
}
};
Module.setStatus('Downloading...');
window.onerror = function(event) {
// TODO: do not warn on ok events like simulating an infinite loop or exitStatus
Module.setStatus('Exception thrown, see JavaScript console');
spinnerElement.style.display = 'none';
Module.setStatus = function(text) {
if (text) Module.printErr('[post-exception status] ' + text);
};
};
</script>
(updated: right code) here is my source of testing site:
https://www.dropbox.com/sh/elgdplx8xmvp51g/AAC-M0oCrA0_rgWZfrRvMt8na?dl=0 look at hello.html
Unfortunately request is not a "standard variable of connection" and is not special in any way. What you probably want is window.onload which is a global event handler available on the window object.
window is a special variable and does have the onload event handler available.
Take a look at the documentation for onload
<script type='text/javascript'>
window.onload = function() {
var bytes = request.response;
fetch('hello.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, importObject)
).then(results => {
// Do something with the results!
console.log(results);
});
};
// Rest of your code ...
Finally a have successfuly build the program and my script now looking just only.
<script src=./a.out.js>
I have update files on my dropbox-link to test project folder for more info. https://www.dropbox.com/sh/elgdplx8xmvp51g/AAC-M0oCrA0_rgWZfrRvMt8na?dl=0
In two words it separate script for two parts in the ending of html page
1st is
<script type='text/javascript'>
var statusElement = document.getElementById('status');
var progressElement = document.getElementById('progress');
var spinnerElement = document.getElementById('spinner');
var Module = {
preRun: [],
postRun: [],
print: (function() {
var element = document.getElementById('output');
if (element) element.value = ''; // clear browser cache
return function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
// These replacements are necessary if you render to raw HTML
//text = text.replace(/&/g, "&");
//text = text.replace(/</g, "<");
//text = text.replace(/>/g, ">");
//text = text.replace('\n', '<br>', 'g');
console.log(text);
if (element) {
element.value += text + "\n";
element.scrollTop = element.scrollHeight; // focus on bottom
}
};
})(),
printErr: function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
if (0) { // XXX disabled for safety typeof dump == 'function') {
dump(text + '\n'); // fast, straight to the real console
} else {
console.error(text);
}
},
canvas: (function() {
var canvas = document.getElementById('canvas');
// As a default initial behavior, pop up an alert when webgl context is lost. To make your
// application robust, you may want to override this behavior before shipping!
// See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2
canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false);
return canvas;
})(),
setStatus: function(text) {
if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' };
if (text === Module.setStatus.text) return;
var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
var now = Date.now();
if (m && now - Date.now() < 30) return; // if this is a progress update, skip it if too soon
if (m) {
text = m[1];
progressElement.value = parseInt(m[2])*100;
progressElement.max = parseInt(m[4])*100;
progressElement.hidden = false;
spinnerElement.hidden = false;
} else {
progressElement.value = null;
progressElement.max = null;
progressElement.hidden = true;
if (!text) spinnerElement.style.display = 'none';
}
statusElement.innerHTML = text;
},
totalDependencies: 0,
monitorRunDependencies: function(left) {
this.totalDependencies = Math.max(this.totalDependencies, left);
Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.');
}
};
Module.setStatus('Downloading...');
window.onerror = function(event) {
// TODO: do not warn on ok events like simulating an infinite loop or exitStatus
Module.setStatus('Exception thrown, see JavaScript console');
spinnerElement.style.display = 'none';
Module.setStatus = function(text) {
if (text) Module.printErr('[post-exception status] ' + text);
};
};
</script>
and the second one is just
<script src=./a.out.js>
full of text you cant see on link to dropbox? its a lot of code to post here
and 3rd this is that i have copy from emscripter git repo html document that it must generate (but in my way not) and also put it to drop box link, to not to spam here.

How to setInterval correct in casperjs?

I try to use webserver talk to outside world and setInterval want its execution automatically every sometimes.
One of my casperjs setting is this.capture(x + 'apple.png');
I though it will show three images under my folder if setInterval run three times.
As the result i only save one image is 1apple.png.
Although i can see a lots of info on my terminal
I want to ask what step should i miss it ? Any help would be appreciated.
Thanks in advance.
Here is my code today.js:
var webserver = require('webserver');
var server = webserver.create();
var service = server.listen('8080', {
'keepAlive': true
}, function (request, response) {
response.statusCode = 200;
response.write('<html><body>What the hell~~</body></html>');
var casper = require("casper").create({
verbose: true,
logLevel: 'debug', // debug, info, warning, error
pageSettings: {
loadImages: false,
loadPlugins: false,
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4'
}
});
var movieTitle = [];
var movieEnTitle = [];
var title = [];
var movieTime = [];
var movieVersion = [];
var city = '台南';
var latitude = 22.993089;
var longitude = 120.196876;
var theaterName = '今日戲院';
var data = {};
data.theater = [];
data.movie = [];
var x =1;
function getMovieTitle() {
var title = document.querySelectorAll('div.theaterlist_name a');
return Array.prototype.map.call(title, function (e) {
return e.innerText;
});
};
function getEnTitle() {
var title = document.querySelectorAll('div.en a');
return Array.prototype.map.call(title, function (e) {
return e.innerText;
});
};
function getMovieTime() {
var title = document.querySelectorAll('ul.theater_time');
return Array.prototype.map.call(title, function (e) {
return e.innerText;
});
};
function getMovieVersion() {
var version = document.querySelectorAll('div.tapR');
return Array.prototype.map.call(version, function (e) {
return e.innerText;
});
};
// 台南 今日戲院 from 奇摩
casper.start('https://tw.movies.yahoo.com/theater_result.html/id=67', function () {
this.echo(this.getTitle());
});
casper.then(function () {
this.echo('Image');
this.echo(x);
this.capture(x + 'apple.png');
x++;
});
casper.then(function () {
movieTitle = this.evaluate(getMovieTitle);
movieEnTitle = this.evaluate(getEnTitle);
movieTime = this.evaluate(getMovieTime);
movieVersion = this.evaluate(getMovieVersion);
});
casper.then(function () {
console.log('Print:\n');
this.echo(movieTitle.length + ' Movie title found :\n');
this.echo(movieTitle.join('\n'));
this.echo(movieEnTitle.length + ' Movie title found :\n');
this.echo(movieEnTitle.join('\n'));
this.echo(movieTime.length + ' Movie time found :\n');
this.echo(movieTime.join('\n'));
this.echo(movieVersion.length + ' Movie version found :\n');
this.echo(movieVersion.join('\n'));
this.echo(outPutJSON());
});
function outPutJSON() {
data.theater.push({
name: theaterName,
city: city,
latitude: latitude,
longitude: longitude
});
// 將中英文名字合併
for (var i = 0; i < movieTitle.length; i++) {
title.push(movieTitle[i] + movieEnTitle[i]);
}
for (var i = 0; i < movieTime.length; i++) {
var name = title[i];
var sourceTime = movieTime[i].match(/.{1,5}/g);
var times = [];
times.push(sourceTime);
var version = movieVersion[i];
data.movie.push({
name: name,
version: version,
time: times
});
}
return JSON.stringify(data);
}
// casper.run(function () {
// // this.echo('Done').exit();
// this.echo('Done');
// });
setInterval(function () {
casper.run(function () {
// this.echo('Done').exit();
this.echo('Done');
});
}, 2000);
response.write(outPutJSON());
response.close();
});
Here is my folder when i command this file , you can see only capture image once 1apple.png.
One way to achieve what you want would be have a cron job scrape the site at the desired frequency and put the results in a directory served by a web server. Below is a stand-alone script that will fetch the title and capture the image of a site once per hour. Modifying this.step is probably unwise (inspiration from this site:
https://github.com/yotsumoto/casperjs-goto )
var casper = require('casper').create();
var x = 0;
casper.start('http://localhost:8080', function() {
// change 'http://localhost:8080' to the site to be scraped
this.echo(this.getTitle());
this.capture(x++ + '.png');
this.wait(60 * 60 * 1000, function() {
// 60 minutes * 60 seconds * 1000 milliseconds
this.step = 0;
});
});
casper.run();

CasperJS - Scraper not navigating to the next page

The following code is a simple scraper written in CasperJS.
var casper = require('casper').create();
var url = casper.cli.get(0);
var page1 = casper.cli.get(1);
var page2 = casper.cli.get(2);
//console.log(page2);
var proxy = casper.cli.get(3);
//alert(page1);
var exp = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(exp);
var baseUrl = url;
//console.log(baseUrl);
var nextBtn = "a.navigation-button.next";
var allLinks = [];
casper.start(baseUrl);
casper.waitForSelector(nextBtn, processPage);
casper.run();
function processPage() {
for (var i = page1; i < page2; i = i + 1) {
console.log(i);
var pageData = this.evaluate(getPageData);
allLinks = allLinks.concat(pageData);
if (!this.exists(nextBtn)) {
return;
};
this.thenClick(nextBtn).then(function() {
//this.echo(i);
this.echo(this.getCurrentUrl());
//this.wait(1000);
});
};
}
function getPageData(){
//return document.title;
var links = document.getElementsByClassName('pro-title');
links = Array.prototype.map.call(links,function(link){
return link.getAttribute('href');
});
return links;
};
casper.then(function(){
//require('utils').dump(allLinks);
this.each(allLinks,function(self,link){
if (link.match(regex)) {
self.thenOpen(link,function(a){
jsonObj = {};
jsonObj.title = this.fetchText('a.profile-full-name');
jsonObj.services = this.getHTML('div.info-list-text span:nth-child(2) span');
jsonObj.services = jsonObj.services.replace(/&/g,"and");
jsonObj.location = this.getHTML('div.pro-info-horizontal-list div.info-list-label:nth-child(3) div.info-list-text span');
//jsonObj.contact = this.fetchText('span.pro-contact-text');
jsonObj.description = this.getHTML('div.profile-about div:nth-child(1)');
//jsonObj.description.replace(/\s/g, '');
//require('utils').dump(jsonObj);
//jsonObj.description = jsonObj.description.replace(/[\t\n]/g,"");
//jsonObj = JSON.stringify(jsonObj, null, '\t');
//console.log(i);
require('utils').dump(jsonObj);
});
};
});
});
I am executing this script as follows,
casperjs scraping.js http://www.houzz.com/professionals/c/Chicago--IL/p/15 1 3
The first CLI argument is the starting URL. The second and third arguments are the starting and ending page numbers of the scrape.
I am able to extract data from the first page, but I don't understand why I am not able to extract data from any of the consequent pages.
You cannot mix synchronous and asynchronous code like this in processPage. The loop is immediately executed, but the click and the loading of the next page happens asynchronously. The evaluation of the page has to be done asynchronously:
function processPage() {
for (var i = page1; i < page2; i = i + 1) {
this.then(function(){
console.log(i);
var pageData = this.evaluate(getPageData);
allLinks = allLinks.concat(pageData);
if (!this.exists(nextBtn)) {
return;
}
this.thenClick(nextBtn).then(function() {
this.echo(this.getCurrentUrl());
});
});
};
}

how to run at command through chrome serial api

i want to run at command at my hardware thorugh crome serial api
I use this Opensource code
https://github.com/GoogleChrome/chrome-app-samples/tree/master/servo
this working only for only integer
i want to pass string in the serial port my code is like following
var connectionId = -1;
function setPosition(position) {
var buffer = new ArrayBuffer(1);
var uint8View = new Uint8Array(buffer);
uint8View[0] = '0'.charCodeAt(0) + position;
chrome.serial.write(connectionId, buffer, function() {});
};
function setTxt(data) {
// document.getElementById('txt').innerHTML = data;
var bf = str2ab(data)
chrome.serial.write(connectionId, bf, function() {});
};
function str2ab(str) {
len = str.length;
var buf = new ArrayBuffer(len*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i<strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
function onRead(readInfo) {
var uint8View = new Uint8Array(readInfo.data);
var value1 = String.fromCharCode(uint8View[0])
var value = uint8View[0] - '0'.charCodeAt(0);
var rotation = value * 18.0;
// var dataarr = String.fromCharCode.apply(null, new Uint16Array(readInfo.data));
//alert(rotation);
if(uint8View[0])
document.getElementById('txt').innerHTML = document.getElementById('txt').innerHTML + value1;
document.getElementById('image').style.webkitTransform =
'rotateZ(' + rotation + 'deg)';
// document.getElementById('txt').innerHTML=uint8View[0];
// Keep on reading.
chrome.serial.read(connectionId, 1, onRead);
};
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function onOpen(openInfo) {
connectionId = openInfo.connectionId;
if (connectionId == -1) {
setStatus('Could not open');
return;
}
setStatus('Connected');
setPosition(0);
chrome.serial.read(connectionId, 1, onRead);
};
function setStatus(status) {
document.getElementById('status').innerText = status;
}
function buildPortPicker(ports) {
var eligiblePorts = ports.filter(function(port) {
return !port.match(/[Bb]luetooth/);
});
var portPicker = document.getElementById('port-picker');
eligiblePorts.forEach(function(port) {
var portOption = document.createElement('option');
portOption.value = portOption.innerText = port;
portPicker.appendChild(portOption);
});
portPicker.onchange = function() {
if (connectionId != -1) {
chrome.serial.close(connectionId, openSelectedPort);
return;
}
openSelectedPort();
};
}
function openSelectedPort() {
var portPicker = document.getElementById('port-picker');
var selectedPort = portPicker.options[portPicker.selectedIndex].value;
chrome.serial.open(selectedPort, onOpen);
}
onload = function() {
var tv = document.getElementById('tv');
navigator.webkitGetUserMedia(
{video: true},
function(stream) {
tv.classList.add('working');
document.getElementById('camera-output').src =
webkitURL.createObjectURL(stream);
},
function() {
tv.classList.add('broken');
});
document.getElementById('position-input').onchange = function() {
setPosition(parseInt(this.value, 10));
};
document.getElementById('txt-input').onchange = function() {
setTxt(this.value);
// document.getElementById('txt').innerHTML = this.value;
};
chrome.serial.getPorts(function(ports) {
buildPortPicker(ports)
openSelectedPort();
});
};
string is the passing through serial but this command not run without enter press how to do it any one know
thanks in advance :)
need a \n at the end of string
example:
writeSerial( '#;Bit_Test;*;1;' + '\n' );
take a look at this project http://www.dataino.it/help/document_tutorial.php?id=13

capture network resource requests on casper.click()

with casper.on("resource.requested"), we can capture the resource requests and perform checks for evaluation.
On page load, we are pushing all the network requests URL in an array and then traverse the array to find the number of calls to GOOGLE Analytics (i.e. _utm.gif).
// google analytics calls testing
casper.test.begin('Test Container Tags', function suite(test) {
casper.start("http://www.viget.com/", function() {
});
var urls = [],
links = [];
casper.on('resource.requested', function(requestData, resource) {
urls.push(decodeURI(requestData.url));
});
casper.then(function() {
var index = -1;
var found = 0;
for (var i = 0; i < urls.length; i++)
{
index = urls[i].indexOf('__utm.gif');
if (index > -1)
found = found+1;
}
casper.echo('found' + found);
test.assert(found > 0, 'Page Load Test Complete');
});
//Emit "resource.requested" to capture the network request on link click
casper.then(function(self) {
var utils = require('utils');
var x = require('casper').selectXPath;
casper.click(x("//a[data-type]"));
casper.emit('resource.requested');
});
casper.run(function() {
test.done();
});
});
But, now the next Ask is to verify the network resource requests on hyperlinks click event. Tried to make that work with casper.emit("resource.requested") but no success.
Already spent one complete day to find the workaround for the same. ANY feedback would be appreciated at this point.
You could use a casper.waitForResource() after the click and do your validation there.
casper.test.begin('Test Container Tags', function suite(test) {
casper.start("http://www.viget.com/", function() {
});
var urls = [],
links = [];
casper.on('resource.requested', function(requestData, resource) {
urls.push(decodeURI(requestData.url));
});
casper.then(function() {
var index = -1;
var found = 0;
for (var i = 0; i < urls.length; i++)
{
index = urls[i].indexOf('__utm.gif');
if (index > -1)
found = found+1;
}
casper.echo('found' + found);
test.assert(found > 0, 'Page Load Test Complete');
});
//Emit "resource.requested" to capture the network request on link click
casper.then(function(self) {
var utils = require('utils');
var x = require('casper').selectXPath;
casper.click(x("//a[data-type]"));
});
casper.waitForResource(function testResource(resource) {
console.log('----->' + resource.url);
});
casper.run(function() {
test.done();
});
});

Categories

Resources