How to click brower prompt in casperjs - phantomjs

I am creating a automated script to do a testing. So when my script try to log out by clicking "log out" it prompt confirmation window where the script has to select 'ok'
Source page looks likes:
<script type="text/javascript">
function logOut() {
if (confirm("Are you sure you want to log out of the system?\nClick OK for Yes or CANCEL for No"))
location.href='ppp_logout.cfm'
}</scrip
My code to click log out and filter the confirm box.
casper.clickLabel('Log Out', 'a');
casper.echo('------$$$ Log Off button clicked', 'INFO');
casper.setFilter('page.confirm', function(msg){
return msg === "Are you sure you want to log out of the system?\nClick OK for Yes or CANCEL for No" ? false : true;
});
reference: http://docs.casperjs.org/en/1.1-beta2/events-filters.html
Allows to react on a javascript confirm() call:
casper.setFilter("page.confirm", function(msg) {
return msg === "Do you like vbscript?" ? false : true;
});
what I am doing wrong

Your ternary operation is backwards.
You can change the following line:
return msg === '...' ? false : true;
... to:
return msg === '...' ? true : false;
... but since the ternary operation is not needed, you can simply write:
return msg === '...';
Full Example:
Consider the following HTML container:
<div id="result"></div>
Now, contemplate the following JavaScript code on the same page:
var result = document.getElementById('result');
if (confirm('Are you sure?')) {
result.textContent = 'Success!';
}
You can use the following CasperJS code to obtain the result:
var casper = require('casper').create();
casper.setFilter('page.confirm', function (message) {
return message === 'Are you sure?';
});
casper.start('https://example.com/', function () {
this.echo(this.getElementInfo('#result').text); // Result: 'Success!'
});
casper.run();

Related

Vue VeeValidate - How to handle exception is custom validation

I have a custom validation in VeeValidate for EU Vat Numbers. It connects to our API, which routes it to the VIES webservice. This webservice is very unstable though, and a lot of errors occur, which results in a 500 response. Right now, I return false when an error has occured, but I was wondering if there was a way to warn the user that something went wrong instead of saying the value is invalid?
Validator.extend('vat', {
getMessage: field => 'The ' + field + ' is invalid.',
validate: async (value) => {
let countryCode = value.substr(0, 2)
let number = value.substr(2, value.length - 2)
try {
const {status, data} = await axios.post('/api/euvat', {countryCode: countryCode, vatNumber: number})
return status === 200 ? data.success : false
} catch (e) {
return false
}
},
}, {immediate: false})
EDIT: Changed code with try-catch.
You can use:
try {
your logic
}
catch(error) {
warn user if API brokes (and maybe inform them to try again)
}
finally {
this is optional (you can for example turn of your loader here)
}
In your case try catch finally block would go into validate method
OK, first of all I don't think that informing user about broken API in a form validation error message is a good idea :-| (I'd use snackbar or something like that ;) )
any way, maybe this will help you out:
I imagine you are extending your form validation in created hook so maybe getting message conditionaly to variable would work. Try this:
created() {
+ let errorOccured = false;
Validator.extend('vat', {
- getMessage: field => 'The ' + field + ' is invalid.',
+ getMessage: field => errorOccured ? `Trouble with API` : `The ${field} is invalid.`,
validate: async (value) => {
let countryCode = value.substr(0, 2)
let number = value.substr(2, value.length - 2)
const {status, data} = await axios.post('/api/euvat', {countryCode: countryCode, vatNumber: number})
+ errorOccured = status !== 200;
return status === 200 ? data.success : false;
},
}, {immediate: false})
}
After searching a lot, I found the best approach to do this. You just have to return an object instead of a boolean with these values:
{
valid: false,
data: { message: 'Some error occured.' }
}
It will override the default message. If you want to return an object with the default message, you can just set the data value to undefined.
Here is a veeValidate v3 version for this:
import { extend } from 'vee-validate';
extend('vat', async function(value) {
const {status, data} = await axios.post('/api/validate-vat', {vat: value})
if (status === 200 && data.valid) {
return true;
}
return 'The {_field_} field must be a valid vat number';
});
This assumes your API Endpoint is returning json: { valid: true } or { valid: false }

How to trigger change event on slate.js when testing with Selenium or Cypress

I'm trying to find a way to simulate a "change" event when doing E2E testing (with selenium or cypress) and slate.js
In our UI, when the user clicks on a word, we pop-up a modal (related to that word). I've been unable to make this happen as I can't get the change event to trigger
The Cypress input commands (e.g. cy.type() and cy.clear()) work by dispatching input and change events - in the case of cy.type(), one per character. This mimics the behavior of a real browser as a user types on their keyboard and is enough to trigger the behavior of most application JavaScript.
However, Slate relies almost exclusively on the beforeinput event (see here https://docs.slatejs.org/concepts/xx-migrating#beforeinput) which is a new browser technology and an event which the Cypress input commands don’t simulate. Hopefully the Cypress team will update their input commands to dispatch the beforeinput event, but until they do I’ve created a couple of simple custom commands which will trigger Slate’s input event listeners and make it respond.
// commands.js
Cypress.Commands.add('getEditor', (selector) => {
return cy.get(selector)
.click();
});
Cypress.Commands.add('typeInSlate', { prevSubject: true }, (subject, text) => {
return cy.wrap(subject)
.then(subject => {
subject[0].dispatchEvent(new InputEvent('beforeinput', { inputType: 'insertText', data: text }));
return subject;
})
});
Cypress.Commands.add('clearInSlate', { prevSubject: true }, (subject) => {
return cy.wrap(subject)
.then(subject => {
subject[0].dispatchEvent(new InputEvent('beforeinput', { inputType: 'deleteHardLineBackward' }))
return subject;
})
});
// slateEditor.spec.js
cy.getEditor('[data-testid=slateEditor1] [contenteditable]')
.typeInSlate('Some input text ');
cy.getEditor('[data-testid=slateEditor2] [contenteditable]')
.clearInSlate()
.typeInSlate('http://httpbin.org/status/409');
If you need to support other inputTypes, all of the inputTypes supported by Slate are listed in the source code for editable.tsx
Found a solution:
1) Add a ref to the Editor
<Editor
ref={this.editor}
/>
2) Add a document listener for a custom event
componentDidMount() {
document.addEventListener("Test_SelectWord", this.onTestSelectWord)
}
componentWillUnmount() {
document.removeEventListener("Test_SelectWord", this.onTestSelectWord)
}
3) Create a handler that creates a custom select event
onTestSelectWord(val: any) {
let slateEditor = val.detail.parentElement.parentElement.parentElement.parentElement
// Events are special, can't use spread or Object.keys
let selectEvent: any = {}
for (let key in val) {
if (key === 'currentTarget') {
selectEvent['currentTarget'] = slateEditor
}
else if (key === 'type') {
selectEvent['type'] = "select"
}
else {
selectEvent[key] = val[key]
}
}
// Make selection
let selection = window.getSelection();
let range = document.createRange();
range.selectNodeContents(val.detail);
selection.removeAllRanges();
selection.addRange(range)
// Fire select event
this.editor.current.onEvent("onSelect", selectEvent)
}
4) User the following in your test code:
arr = Array.from(document.querySelectorAll(".cl-token-node"))
text = arr.filter(element => element.children[0].innerText === "*WORD_YOU_ARE_SELECTING*")[0].children[0].children[0]
var event = new CustomEvent("Test_SelectWord", {detail: text})
document.dispatchEvent(event, text)
Cypress can explicitly trigger events: https://docs.cypress.io/api/commands/trigger.html#Syntax
This may work for you:
cy.get(#element).trigger("change")

Office.context.roamingSettings.saveAsync function gives a error when using Dialog API for Office Add-in

i get following error when saving roaming setting value.this Office.initialize method is defined in a dialog box window(myDialog.html) and it is called using
Office.context.ui.displayDialogAsync('https://myAddinDomain/myDialog.html');
Office.initialize = function (reason) {
$(document).ready(function () {
//console.log("Sending auth complete message through dialog: " + oauthResult.authStatus);
Office.context.roamingSettings.set("o365auth", 'yyryy');
Office.context.roamingSettings.saveAsync(function (asyncResult) {
if (asyncResult.status === "success") {
var dataValue = result.value; // Get selected data.
} else {
var err = result.error;
}
});
});
}
error says "
Uncaught TypeError: Cannot read property 'invoke' of null
at window.OSF.DDA.OutlookAppOm.u.DDA.OutlookAppOm.invokeHostMethod "
Currently, we only support the Office.context.ui.messageParent API inside the dialog.

CasperJS: exit not working

Trying to open random pages through casperJS start method but some pages are loading properly and some of them are not, so in this scenario it is not exiting from casperjs.
It is getting stuck in console then need to manually exit from console using CTR+C.
casper.start("some url", function() {
if(this.status().currentHTTPStatus == 200) {
casper.echo("page is loading");
} else {
casper.echo("page is in error ");
this.exit();
}
});
Wrap it by a then step with a global stepTimeout option.
Sample code:
var casper = require('casper').create({
stepTimeout: 10000 //10s
})
casper.start()
casper.then(funtion(){
casper.open(url)
})
casper.run()
Try bypass() to ignore the next thens.
casper.start("some url", function() {
if(this.status().currentHTTPStatus == 200) {
casper.echo("page is loading");
} else {
casper.echo("page is in error ");
this.bypass(2); // Will not execute the then functions.
}
}).then(function() {
// The 1st then function.
}).then(function() {
// The 2nd then function.
})
casper.run(function() {
this.echo('Something');
this.exit(); // <--- Here.
});

Triggering remove event of kendo upload on click of button is not working

I want to remove selected file of kendo upload control on click event of another button and I followed the below link
Triggering OnCancel event of kendo upload on click of button the remove event fired but not clear the file below is my code. please can any one help me what i am doing wrong.
$(document).ready(function () {
$("#files").kendoUpload({
"multiple": false,
select: function (event) {
console.log(event);
var notAllowed = false;
$.each(event.files, function (index, value) {
if ((value.extension).toLowerCase() !== '.jpg') {
alert("not allowed! only jpg files!");
notAllowed = true;
}
else if (value.size > 3000000) {
alert("file size must less than 3MB ");
notAllowed = true;
}
if (event.files.length > 1) {
alert("Please select single file.");
e.preventDefault();
}
});
var breakPoint = 0;
if (notAllowed == true) event.preventDefault();
var fileReader = new FileReader();
fileReader.onload = function (event) {
var mapImage = event.target.result;
$("#sigimage").attr('src', mapImage);
document.getElementById("sigimage").style.display = 'block';
}
fileReader.readAsDataURL(event.files[0].rawFile);
},
remove: function (e) {
alert("remove");
e.preventDefault();
},
});
$("#closewindow").click(function (e) {
$("#files").data("kendoUpload").trigger("remove");
});
});
You can use the following code for removing the file inside your click function.
$(".k-delete").parent().click();
Please visit the fiddle here for a working example
You can create your custom function like this:
function remove(){
$(".k-upload-files").remove();
$(".k-upload-status").remove();
$(".k-upload.k-header").addClass("k-upload-empty");
$(".k-upload-button").removeClass("k-state-focused");
};
It will delete trigger delete of uploaded files.