How to get separate out characters from within a string - javascript

I have a string:
string = "abc_test_dashboard.json";
The value of string could vary like:
"tes.test.dashboard.json"
"jhgwefj-gfjh.widget.json"
The last "dashboard.json" and "widget.json" is static and could be either of them depending on a condition.
Basically I'm trying to identify if its "dashboard" or "widget" from the string.
I want to do stuff based on:
if ("dashboard.json") {//do some stuff}
else { // do something else
}
I also just realized that I may have multiple files with same name, and hence I may end up getting (1), (2) suffixes i.e: "abc_test_dashboard(1).json", "abc_test_dashboard(2).json". is there any way to test these kind of scenarios?
Thanks

You can do it with
if(string.endsWith('dashboard.json')) {
}
if(string.endsWith('widget.json')) {
}
Also you can use regex if you want (in case your target browsers do not support endsWith);
if (/widget\.json$/.test('widget.json')) {
}
Using regex you can even extract the initial portion of the file;
var widgetInfo = 'asd.widget.json'.match(/^(.*)widget\.json$/)
if (widgetInfo) {
console.log(widgetInfo[1]) // will print `asd.`
}
// similar code to check for `dashboard.json`
EDIT:
In the case you commented you can use the following regex; /^(.*)widget(\(.+\))?\.json$/. It will match strings in the forms of randomstring.widget.json and randomstring.widget(1).json, but not randomstring.widget().json

If you don't mind RegEx, you can use the String match() method as in the below:
function checkStrEnd(str) {
if (str.match(/dashboard\.json$/)) {
console.log('Do dashboard stuff');
} else if (str.match(/widget\.json$/)) {
console.log('Do widget stuff');
} else {
console.log('Do something else');
}
}
checkStrEnd('tes.test.dashboard.json'); // 'Do dashboard stuff'
checkStrEnd('jhgwefj-gfjh.widget.json'); // 'Do widget stuff'
checkStrEnd('random string'); // 'Do something else'

you can use includes to see if the string exists within the string
let arr = ["tes.test.dashboard.json", "jhgwefj-gfjh.widget.json"]
arr.forEach(item => {
if (item.includes('dashboard.json')) {
console.log('dasboard')
} else if (item.includes('widget.json')) {
console.log('widget')
}
})

Related

If/else condition in Cypress not working as expected

I have this code
Cypress.Commands.add('VerifyLoginState', () => {
if(cy.contains('Login')) {
cy.get('.form-control').eq(0).type('firstfield')
cy.get('.form-control').eq(1).type('secondfield')
cy.get('.btn-login').click()
cy.wait(2500)
cy.contains('Upcoming Appointments').should('be.visible')
}
else
{
cy.contains('Appointment summary').should('be.visible')
}
})
How should I write the code so that it can pass to the condition of else, when I am authenticated in the browser and the condition of if is not valid?
In other words, I want to check if an element is present on the page, and even if it is not present, the code should not give an error and move on
Cypress yields the result of cy functions, and does not return them. So your if/else will not work as it would in traditional JavaScript. Check out this article from Cypress about conditional testing.
Something like the following should help you out:
// Get the body of the DOM
cy.get('body').then(($body) => {
// Check if the body contains the `Login` element
if ($body.contains('Login').length) {
cy.get('.form-control').eq(0).type('firstfield')
cy.get('.form-control').eq(1).type('secondfield')
cy.get('.btn-login').click()
cy.wait(2500)
cy.contains('Upcoming Appointments').should('be.visible')
} else {
cy.contains('Appointment summary').should('be.visible')
}
Another option is to use within
ref: https://docs.cypress.io/api/commands/within#Syntax
cy.contains('Login')
.within(() => {
cy.get('.form-control').eq(0).type('firstfield')
cy.get('.form-control').eq(1).type('secondfield')
cy.get('.btn-login').click()
cy.wait(2500)
cy.contains('Upcoming Appointments').should('be.visible')
})
You may find it easier to test for either/or text using jQuery :contains and multiple selectors separated by a comma
cy.get('body')
.children(':contains(Login), :contains(Appointment summary)') // only one is on the page
.invoke('text')
.then(labelText => {
if (labelText.trim() === 'Login') {
cy.get('.form-control').eq(0).type('firstfield')
... etc
} else {
cy.contains('Appointment summary').should('be.visible')
}
})

Custom URL validation using Javascript RegExp

I created a function that should check if a string correspond to an url format:
const test = (str) => {
const t = new RegExp(
'^(https?:\\/\\/)?' +
'(www\\.)' +
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|)' +
'(\\#[-a-z\\d_]*)?$',
'i',
);
return t.test(str);
};
console.log(test('http://demo.com')); //expect true
console.log(test('http://ww.demo.com')); //expect false
For each console.log() i wrote the expected value, in both cases i got false. In the last case false is ok, but in the first i should get true. How to fix the regex?
Even if this answer is a bit too much for this Problem, it illustrates the problem: Even if it might be possible to create a regexp to check the url, it is much simpler and more robust to parse the URL and "create a real Object", on/with which the overall test can be decomposed to a number of smaller tests.
So probably the builtin URL constructor of modern browsers may help you here (link1, link 2).
One approach to test you url might look like this:
function testURL (urlstring) {
var errors = [];
try {
var url = new URL(urlstring);
if (!/https/.test(url.protocol)) {
errors.push('wrong protocol');
}
//more tests here
} catch(err) {
//something went really wrong
//log the error here
} finally {
return errors;
}
}if (testURL('mr.bean').length == 0) { runSomething(); }

How to check if element exists using Cypress.io

How to check if element is present or not, so that certain steps can be performed if element is present. Else certain different steps can be performed if element is not present.
I tried something like below but it didn't work:
Cypress.Commands.add('deleteSometheingFunction', () => {
cy.get('body').then($body => {
if ($body.find(selectors.ruleCard).length) {
let count = 0;
cy.get(selectors.ruleCard)
.each(() => count++)
.then(() => {
while (count-- > 0) {
cy.get('body')
// ...
// ...
}
});
}
});
});
I am looking for a simple solution, which can be incorporated with simple javascript
if else block or then() section of the promise
Something similar to Webdriver protocol's below implementions:
driver.findElements(By.yourLocator).size() > 0
check for presenece of element in wait
Kindly advise. Thanks
I'll just add that if you decide to do if condition by checking the .length property of cy.find command, you need to respect the asynchronous nature of cypress.
Example:
Following condition evaluates as false despite appDrawerOpener button exists
if (cy.find("button[data-cy=appDrawerOpener]").length > 0) //evaluates as false
But this one evaluates as true because $body variable is already resolved as you're in .then() part of the promise:
cy.get("body").then($body => {
if ($body.find("button[data-cy=appDrawerOpener]").length > 0) {
//evaluates as true
}
});
Read more in Cypress documentation on conditional testing
it has been questioned before: Conditional statement in cypress
Thus you can basically try this:
cy.get('header').then(($a) => {
if ($a.text().includes('Account')) {
cy.contains('Account')
.click({force:true})
} else if ($a.text().includes('Sign')) {
cy.contains('Sign In')
.click({force:true})
} else {
cy.get('.navUser-item--account .navUser-action').click({force:true})
}
})
cypress all steps are async ,, so that you should make common function in commands file or page object file,,..
export function checkIfEleExists(ele){
return new Promise((resolve,reject)=>{
/// here if ele exists or not
cy.get('body').find( ele ).its('length').then(res=>{
if(res > 0){
//// do task that you want to perform
cy.get(ele).select('100').wait(2000);
resolve();
}else{
reject();
}
});
})
}
// here check if select[aria-label="rows per page"] exists
cy.checkIfEleExists('select[aria-label="rows per page"]')
.then(e=>{
//// now do what if that element is in ,,..
})
.catch(e=>{
////// if not exists...
})
I found a solution, hope it helps!
You can use this:
cy.window().then((win) => {
const identifiedElement = win.document.querySelector(element)
cy.log('Object value = ' + identifiedElement)
});
You can add this to your commands.js file in Cypress
Cypress.Commands.add('isElementExist', (element) => {
cy.window().then((win) => {
const identifiedElement = win.document.querySelector(element)
cy.log('Object value = ' + identifiedElement)
});
})
Cypress official document has offered a solution addressing the exact issue.
How to check Element existence
// click the button causing the new
// elements to appear
cy.get('button').click()
cy.get('body')
.then(($body) => {
// synchronously query from body
// to find which element was created
if ($body.find('input').length) {
// input was found, do something else here
return 'input'
}
// else assume it was textarea
return 'textarea'
})
.then((selector) => {
// selector is a string that represents
// the selector we could use to find it
cy.get(selector).type(`found the element by selector ${selector}`)
})
For me the following command is working for testing a VS code extension inside Code server:
Cypress.Commands.add('elementExists', (selector) => {
return cy.window().then($window => $window.document.querySelector(selector));
});
And I'm using it like this in my E2E test for a Code Server extension:
cy.visit("http://localhost:8080");
cy.wait(10000); // just an example here, better use iframe loaded & Promise.all
cy.elementExists("a[title='Yes, I trust the authors']").then((confirmBtn) => {
if(confirmBtn) {
cy.wrap(confirmBtn).click();
}
});
Just ensure that you're calling this check once everything is loaded.
If you're using Tyepscript, add the following to your global type definitions:
declare global {
namespace Cypress {
interface Chainable<Subject> {
/**
* Check if element exits
*
* #example cy.elementExists("#your-id").then($el => 'do something with the element');
*/
elementExists(element: string): Chainable<Subject>
}
}
}
Aside
VS Code server relies heavily on Iframes which can be hard to test. The following blog post will give you an idea - Testing iframes with Cypress.
The above code is needed to dismiss the "trust modal" if it's shown. Once the feature disable-workspace-trust is released it could be disabled as CLI option.
This command throws no error if element does not exist. If it does, it returns the actual element.
cypress/support/commands.js
elementExists(selector) {
cy.get('body').then(($body) => {
if ($body.find(selector).length) {
return cy.get(selector)
} else {
// Throws no error when element not found
assert.isOk('OK', 'Element does not exist.')
}
})
},
Usage:
cy.elementExists('#someSelectorId').then(($element) => {
// your code if element exists
})
In case somebody is looking for a way to use cy.contains to find an element and interact with it based on the result. See this post for more details about conditional testing.
Use case for me was that user is prompted with options, but when there are too many options, an extra click on a 'show more' button needs to be done before the 'desired option' could be clicked.
Command:
Cypress.Commands.add('clickElementWhenFound', (
content: string,
) => {
cy.contains(content)
// prevent previous line assertion from triggering
.should((_) => {})
.then(($element) => {
if (!($element || []).length) {
/** Do something when element was not found */
} else {
cy.contains(content).click();
}
});
});
Usage:
// Click button with 'Submit' text if it exists
cy.clickElementWhenFound('Submit');
Using async/await gives a clean syntax:
const $el = await cy.find("selector")
if ($el.length > 0) {
...
More info here: https://medium.com/#NicholasBoll/cypress-io-using-async-and-await-4034e9bab207
I had the same issue like button can appear in the webpage or not. I fixed it using the below code.
export function clickIfExist(element) {
cy.get('body').then((body) => {
cy.wait(5000).then(() => {
if (body.find(element).length > 0) {
cy.log('Element found, proceeding with test')
cy.get(element).click()
} else {
cy.log('Element not found, skipping test')
}
})
})
}

Customxmlnode: is there a way to get a single node using office js?

I noticed that with VBO you can call the method getSingleNode to get a specific node object, is it possible to do something similar with office js?
Also, I have a radio button value in my Word metadata, I managed to access its customxmlnode object, then I used setTextsync method to change its value from true to false, but the new value I get for my radio button metadata is empty. Other text type metadata could be edited correctly though.
Could anyone give some suggestions?
function EditCTF() {
//$("#fields").css({ display: "" });
Word.run(function(context) {
context.document.properties.title = $("#Title").val();
Office.context.document.customXmlParts.getByNamespaceAsync(
"http://schemas.microsoft.com/office/2006/metadata/properties",
function(asyncResult) {
if (asyncResult.value.length > 0) {
var xmlPart = asyncResult.value[0];
xmlPart.getNodesAsync("*/*", function(nodeResults) {
console.log(nodeResults.value.length);
for (i = 0; i < nodeResults.value.length; i++) {
var node = nodeResults.value[i];
node.getTextAsync({ asyncContext: "StateNormal" }, function(result) {
console.log(result);
console.log(result.value);
});
console.log("NewValue");
if (node.baseName == "Address") {
node.setTextAsync(
$("#Address").val(),
{
asyncContext: "StateNormal"
},
function(newresult) {}
);
}
if (node.baseName == "MainContactPerson") {
node.setTextAsync(
$("#Main Contact Person").val(),
{
asyncContext: "StateNormal"
},
function(newresult) {}
);
}
if (node.baseName == "GDPR") {
node.setTextAsync(
"true",
{
asyncContext: "StateNormal"
},
function(newresult) {
console.log(newresult);
console.log(newresult.value);
}
);
}
}
});
}
}
);
return context.sync().then(function() {});
});
}
The correct XPATH format is not an intuitive format, and it does not help that the Microsoft API documentation provide dumb examples that use wildcard (/) xpaths, like so:
xmlPart.getNodesAsync('*', function (nodeResults)
OfficeJS (or perhaps, SharePoint) injects namespace aliases into the mix (ie /ns3:...), so you were on the right track, but to get the 'CGI_Address' SharePoint document property, you need this XPATH syntax:
var xpath = "/ns0:properties[1]/documentManagement[1]/ns3:CGI_Address[1]";
xmlPart.getNodesAsync(xpath, ...);
GOTCHA: When making significant schema changes to the SharePoint content types that the Word document is based on, it may suddenly change the namespace alias from "ns3" to "ns4" or indeed, from "ns4" back to "ns3" like what happened to me today - go figure?!?
And it seems that the OfficeJS API does not properly implement XPATH, as trying to wildcard the namespace alias (so it can accept /ns3 or /ns4 etc) with /*:CGI_Address1 doesn't work.
SO Reference (as to why it should work) - how to ignore namespaces with XPath
Please use the XPATH expression you send in the xmlPart.getNodesAsync("/", function(nodeResults) method. The first parameter is an XPath expression you can use to get the single node you need.

How to validate data with usage logic in Azure mobile service

My problem is how do I validate data. I don't know JS, so I tried do in this way:
function insert(item, user, request) {
if(typeof item.NamePlayer!=='empty') // in app default value is 'empty'
{
request.execute();
}
}
Does JS have a contain method on a table? For example I want a response to table 'NamePlayer' and not add an item with the same value.
Your condition will always be true. The operator typeof will return one of the following values: "number," "string," "boolean," "object," "function," and "undefined." - so it will never be "empty". If you want to check whether the item.NamePlayer is not empty, you can use the condition below:
if (item.NamePlayer !== '') {
// ...
}
You can also simplify the condition, which will also catch the case where the client didn't send a NamePlayer value in the input:
if (item.NamePlayer) {
// ...
}
One more thing: your script will only dealing with the "positive" case; it also needs to send a response in case the condition fails. Something like the code below:
function insert(item, user, request) {
if (item.NamePlayer) {
request.execute();
} else {
request.respond(400, 'NamePlayer is required');
}
}

Categories

Resources