do nested loops in Casperjs - casperjs

I am new in Casperjs and I would like do dinamic testing depending on external data sources. But, I am experiencing some problems with the loops.
This is my code:
var url = ['http://google.com/','http://www.as.com'];
casper.test.begin('PruebaLoop', function (test) {
casper.start('about:blank',function() {
});
casper.then(function() {
casper.viewport(1024, 768);
//casper.echo(casper.getTitle());
});
console.log('url.length: ' + url.length)
for (i = 0; i < url.length; i++) {
casper.thenOpen(url[i], function() { // open that link
console.log('i: '+i);
});
casper.wait(5000, function() {
this.echo("I've waited for a 5 seconds.");
});
casper.then(function() {
casper.capture('url'+i+'.png');
});
}
casper.run(function() {
casper.echo('Test completado');
casper.test.done();
});
});
From debugging, I always get 2 as the result. I don't know why. Could you please offer me some help?
Thanks a lot!

my solution is:
var urls = ['http://www.elpais.es','http://www.as.com'];
casper.test.begin('PruebaLoop', function (test) {
casper.start('auto:blank',function() {
console.log("-----------------------------------");
console.log("estoy en start ");
});
casper.then(function() {
casper.viewport(1024, 768);
console.log("estoy en wiewport");
console.log("urls.length = " + urls.length);
console.log("-----------------------------------");
});
for(i = 0; i < urls.length; i++) {
(function(index) {
var url = urls[index]
casper.thenOpen(url, function() {
console.log('index tiene el valor: '+ index);
console.log('i tiene el valor: '+ i);
});
casper.then(function() {
this.wait(5000);
console.log("estoy en wait: "+ index);
});
casper.then(function() {
this.wait(5000);
casper.capture("pagina"+index+".png");
console.log("estoy en capture: " + index);
console.log("-----------------------------------");
});
})(i);
}
casper.run(function() {
casper.echo('Test completado');
casper.test.done();
});
});
it works.

Related

laravel set up ckeditor/ckeditor5-export-pdf

I try to set up plugin ckeditor/ckeditor5-export-pdf on my Laravel App But I cant do this. I still get issues like: Uncaught TypeError: Failed to resolve module specifier "#ckeditor/ckeditor5-export-pdf/src/exportpdf". Relative references must start with either "/", "./", or "../".
I did all steps as in docs: https://ckeditor.com/docs/ckeditor5/latest/features/export-pdf.html#configuration But when I try use import ExportPdf from '#ckeditor/ckeditor5-export-pdf/src/exportpdf'; I get the error like above. Please help. Maybe some have stuck on this issue before
import ExportPdf from '#ckeditor/ckeditor5-export-pdf/src/exportpdf';
console.log(ExportPdf);
$(document).ready(function () {
/*function ExportPdf(editor) {
editor.execute('exportPdf');
}*/
function SimpleUploadAdapter(editor) {
editor.plugins.get('FileRepository').createUploadAdapter = function(loader) {
return {
upload: function() {
return loader.file
.then(function (file) {
return new Promise(function(resolve, reject) {
// Init request
var xhr = new XMLHttpRequest();
xhr.open('POST', '/admin/instructions/ckmedia', true);
xhr.setRequestHeader('x-csrf-token', window._token);
xhr.setRequestHeader('Accept', 'application/json');
xhr.responseType = 'json';
// Init listeners
var genericErrorText = `Couldn't upload file: ${ file.name }.`;
xhr.addEventListener('error', function() { reject(genericErrorText) });
xhr.addEventListener('abort', function() { reject() });
xhr.addEventListener('load', function() {
var response = xhr.response;
if (!response || xhr.status !== 201) {
return reject(response && response.message ? `${genericErrorText}\n${xhr.status} ${response.message}` : `${genericErrorText}\n ${xhr.status} ${xhr.statusText}`);
}
$('form').append('<input type="hidden" name="ck-media[]" value="' + response.id + '">');
resolve({ default: response.url });
});
if (xhr.upload) {
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
loader.uploadTotal = e.total;
loader.uploaded = e.loaded;
}
});
}
// Send request
var data = new FormData();
data.append('upload', file);
data.append('crud_id', {{ $instruction->id ?? 0 }});
xhr.send(data);
});
})
}
};
}
}
var allEditors = document.querySelectorAll('.ckeditor');
for (var i = 0; i < allEditors.length; ++i) {
ClassicEditor.create(
allEditors[i], {
extraPlugins: [SimpleUploadAdapter, /*ExportPdf*/],
/*toolbar: [
'exportPdf', '|',
],
exportPdf: {
stylesheets: [
'./path/to/fonts.css',
'EDITOR_STYLES',
'./path/to/style.css'
],
fileName: 'my-file.pdf',
converterOptions: {
format: 'A4',
margin_top: '20mm',
margin_bottom: '20mm',
margin_right: '12mm',
margin_left: '12mm',
page_orientation: 'portrait'
}
}*/
}
);
}
});
</script>```
I solved my problem with https://ckeditor.com/ckeditor-5/online-builder/ Builded what I want and setup it on my App

How to set right path on localhost

Hey Guys,
I have a problem to show my picture on my Page.
I dont know how to set the right path to show my picture.
I use socket.io and express. The Page is running on a Localhost Server
this is my code to show the picture but it doesnt works.
img src="uploads/images.png"
On the server-side i did this "app.use(express.static('public'));" to make it public. But it doesnt work, can someone help me ?
What is the right path?
My Folder structure is this
Folder structure
Server-side:
var app = require('express')();
var express = require('express');
var upload = require('express-fileupload');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var multer = require('multer');
var fs = require('fs');
app.use(upload());
app.use(express.static('public'));
var users = {};
var allUsers = [];
function actualTime(){
var d = new Date();
return d.toLocaleTimeString();}
http.listen(3000, function(){
console.log('listening on *:3000');
});
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
app.post('/upload',function(req,res){
console.log(req.files);
if(req.files.upfile){
var file = req.files.upfile,
name = file.name,
type = file.mimetype;
var uploadpath = __dirname + '/uploads/' + name;
file.mv(uploadpath,function(err){
if(err){
console.log("File Upload Failed",name,err);
res.send("Error Occured!")
}
else {
console.log("File Uploaded",name);
console.log("guckmal");
io.emit('file', name);
res.send('sasa');
}
});
}
else {
res.send("No File selected !");
res.end();
};
})
socket.on('username', function(data,callback){
if(data in users || data.length<=2){
callback(false);
}else{
callback(true);
socket.nickname = data;
users[socket.nickname] = socket;
// to get a message for all users who are not in the priavte chat
allUsers.push(""+socket.nickname);
for(var test=0; test<allUsers.length;test++){
console.log(allUsers[test]);
users[allUsers[test]].emit('usernames', {list:Object.keys(users), nick: allUsers[test]});
}
io.emit('chat message',{msg:"joined the Chatroom", nick:socket.nickname, time:actualTime()});
}
});
socket.on('chat message', function(data, callback){
console.log(socket.nickname);
console.log('User: ' + socket.nickname + ' message: ' + data);
var msg = data.trim();
if(msg.substr(0,3)=== '/w '){
console.log("private chat");
msg= msg.substr(3);
var temp = msg.indexOf(' ');
if(temp !== -1){
console.log("private chat stap 2");
var name = msg.substring(0,temp);
var msg = msg.substring(temp+1);
if(name in users){
console.log("private chat stap 3");
users[name].emit('private chat', {msg:msg, nick:socket.nickname, time:actualTime()});
for(var i=0; i<allUsers.length;i++){
if((name !==allUsers[i])){
if(allUsers[i] !== socket.nickname){
users[allUsers[i]].emit('private chat',{msg:"private message was send from "+socket.nickname+" to "+name, nick:socket.nickname, time:actualTime()});
}else{
users[socket.nickname].emit('private chat',{msg:"you send a private messgae to "+name, nick:"chat", time:actualTime()});
}
}
}
}else{
callback(' user name doesnt exist');
}
}else{
callback('Error! Please enter a message');
}
}else{
io.emit('chat message', {msg:msg, nick:socket.nickname, time:actualTime()});
}
});
socket.on('disconnect', function(data){
delete users[socket.nickname];
io.emit('chat message',{msg:"leaved the Chatroom", nick:socket.nickname, time:actualTime()});
io.sockets.emit('usernames', {list:Object.keys(users)});
});
});
Client-side:
$(function () {
var socket = io();
$('#loginForm').submit(function(e){
e.preventDefault(); // prevents page reloading
socket.emit('username', $('#u').val(), function(data,callback){
if(data){
$('#nickWrap').hide();
$('#contentWrap').show();
}else if(($('#u').val()).length<=2){
document.getElementById("u").value="";
document.getElementById("u").placeholder ="Sorry but Username length is less then three :(";
}else{
document.getElementById("u").value="";
document.getElementById("u").placeholder ="Sorry but Username already taken :(";
}
});
});
$('#chatForm').submit(function(e){
e.preventDefault(); // prevents page reloading
if(privateUsers.length>0){
for(var i=0;i<privateUsers.length;i++){
socket.emit('chat message','/w '+ privateUsers[i] +' '+ $('#m').val(), function(data){
// add stuff later
$('#messages').append($('<li>').text(data.time + " " + data.nick +': '+ data.msg ));
});
}
}else{
socket.emit('chat message', $('#m').val(), function(data){
// add stuff later
$('#messages').append($('<li>').text(data.time + " " + data.nick+': '+ data.msg ));
});
}
$('#m').val('');
return false;
});
socket.on('chat message', function(data){
$('#messages').append($('<li>').text(data.time + " " + data.nick +': '+ data.msg ));
});
socket.on('file', function(data){
var img = document.getElementById('bild');
images.push[data];
var name = data;
console.log(name);
$('#messages').append('<li><img src="uploads/images.png" />'+ '</li>');
img.setAttribute('src','data:image/jpeg;base64,' + window.btoa(images));
});
socket.on('private chat', function(data){
$('#messages').append($('<li>').text(data.time + " " + data.nick +': '+ data.msg ));
});
socket.on('usernames', function(socket, data){
console.log("2222222222");
// to get a massage for all users who are not in the priavte chat
console.log(socket.nick);
socketName = socket.nick;
});
socket.on('usernames', function(data){
document.getElementById("userList").innerHTML = "";
var temp;
var indexTemp;
var me= "";
var sortData = [];
for(var i=0;i<data.list.length;i++){
if(data.nick === data.list[i]){
indexTemp = i;
/* temp = data.list[i];
indexTemp =i;
data.list[i]= "Ich";*/
me ="My Name: ";
}
}
// sort list
sortData.push(data.list[indexTemp]);
for(var l=0; l<data.list.length;l++){
if(indexTemp !=l){
sortData.push(data.list[l]);
}
}
for(var i =0; i<sortData.length;i++){
if(i==0){
$('#userList').append('<li style="list-style:none "><buttonid="'+sortData[i]+'" onclick='+'"addUsers()"'+
' style="width: 100%; background: rgb(130, 224, 255); border: none; padding:10%; margin-bottom:2%; "'+'>'+"My Name: "+ sortData[i]
+'</button></li>');
//data.list[i]= temp;
}else{
$('#userList').append('<li style="list-style:none "><button id="'+sortData[i]+'" onclick='+'"addUsers(\''+sortData[i]+'\')"'+
' style="width: 100%; background: rgb(130, 224, 255); border: none; padding:10%; margin-bottom:2%; "'+'>'+ sortData[i]
+'</button></li>');
}
}
// }
});
});
function addUsers(name){
if(privateUsers.length==0){
console.log("erstes objekt");
document.getElementById(name).style.background = "rgb(1, 254, 185)";
privateUsers.push(name);
}else{
for(var i=0;i<privateUsers.length;i++){
if(name==privateUsers[i]){
console.log("gel�scht");
document.getElementById(name).style.background = "rgb(130, 224, 255)";
privateUsers.splice(i,1);
return;
}
}
console.log("drinnen");
document.getElementById(name).style.background = "rgb(1, 254, 185)";
privateUsers.push(name);
}
}

How to specify spec names to screenshots for each test run in protractor

I am using protractor framework & jasmine-allure-reporter to create report and take screenshot.
jasmine.getEnv().addReporter(new AllureReporter({
resultsDir: 'allure-results'
}));
jasmine.getEnv().afterEach(function (done) {
browser.takeScreenshot().then(function (png) {
allure.createAttachment('Screenshot', function () {
return new Buffer(png, 'base64')
}, 'image/png')();
done();
})
});
}
Is there a provision to customize the screenshot name for each test? Currently it has some random number as the image name(0a8bbc5e-35ee-4d7f-be8b-532fe4a1b4a8-attachment.png) instead i want something like this (<specname>.png). Is it possible to do that? Can someone please help me with this?
var today = new Date();
var timeStamp = today.getMonth() + 1 + '-' + today.getDate() + '-' + today.getFullYear() + '-' + today.getHours() + 'h-' + today.getMinutes() + 'm-' + today.getSeconds() + 's';
ScreenShotName = 'MaGE_Admin' + '-' + timeStamp;
jasmine.getEnv().addReporter(reporter);
jasmine.getEnv().topSuite().afterEach({
fn: async function () {
try {
await browser.takeScreenshot().then(function (png) {
allure.createAttachment(ScreenShotName, new Buffer.from(png, 'base64'));
});
} catch (e) {
console.log(e);
}
}
});
You could do something like this:
jasmine.getEnv().addReporter(new AllureReporter({
resultsDir: 'allure-results'
}));
jasmine.getEnv().afterEach(function (done) {
browser.takeScreenshot().then(function (png) {
allure.createAttachment(exports.config.multiCapabilities.name, function () {
return new Buffer(png, 'base64')
}, 'image/png')();
done();
})
});
}
That worked for me.

Jasmine looping tests

I have written a NodeJs client that generates API requests for various combinations and stores the responses in an array. By looping a Jasmine script I am trying to assert them. However my tests run before it initialize the API responses array. I have tried two approaches and no luck so far.
Approach 1:
var answersReq = require('../requests/answers_request');
var data = answersReq.answers(function(results) {
return results;
})
describe("Answer API test", function() {
function runTest(context) {
describe("test array suite", function() {
it("test array", function(done) {
expect(context).not.toBeNull();
done();
});
});
}
for (i = 0; i <= data.length; i++) {
runTest(data[i]);
}
});
Approach 2:
var answersReq = require('../requests/answers_request');
var data;
describe("Answer API test", function() {
beforeAll(function(done) {
data = answersReq.answers(function(results) {
data = results;
done();
})
});
function runTest(context) {
describe("test array suite", function() {
it("test array", function(done) {
expect(context).not.toBeNull();
done();
});
});
}
for (i = 0; i <= data.length; i++) {
runTest(data[i]);
}
});
works for me, double check what's in data
/*** CODE ***/
var data = [1,1,1,1,1]
describe("Answer API test", function() {
function runTest(context) {
describe("test array suite", function() {
it("test array", function(done) {
expect(context).not.toBeNull();
done();
});
});
}
for (i = 0; i <= data.length; i++) {
runTest(data[i]);
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine-html.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/boot.min.js"></script>

NativeScript HTTP:getJSON doesn't work

I have used the original helloworld app and just change the model from HelloWorldModel to MainModel.
Then i required "http" but when i run the app and klik the button for "updateAction" it only writes to the console and sets the message.
The HTTP request doesn't do anything.
Code: (main-view-model.js)
var __extends = this.__extends || function(d, b) {
for (var p in b)
if (b.hasOwnProperty(p)) d[p] = b[p];
function __() {
this.constructor = d;
}
__.prototype = b.prototype;
d.prototype = new __();
};
var observable = require("data/observable");
var http = require("http");
var MainModel = (function(_super) {
__extends(MainModel, _super);
function MainModel() {
_super.call(this);
console.log("MainModel called");
this.set("message", "Last updated" + " 2015-07-22 00:00:00");
this.set("message2", "Last updated" + " 2015-07-22 00:00:00");
}
MainModel.prototype.updateAction = function() {
console.log("updateAction");
this.set("message2", "Last updated" + " 2015-07-22 01:00:00");
http.getJSON("https://httpbin.org/get").then(function(r) {
this.set("message", "Last updated \n" + r);
console.log("SUCCESS");
console.log(r);
}, function(e) {
// Argument (e) is Error!
console.log("FAIL");
console.log(e);
this.set("message", "Last updated \n" + e);
});
};
return MainModel;
})(observable.Observable);
exports.MainModel = MainModel;
exports.mainViewModel = new MainModel();
What am I doing wrong?
Note: I'm testing on iPhone 6 emulator
It seems that using getString works and gives the same response.
Still wierd the getJSON doesn't work.
A working example is:
http.getString("https://httpbin.org/get").then(function (r) {
console.log("SUCCESS");
console.log(r);
}, function (e) {
console.log("FAIL");
console.log(e);
});

Resources