how to assert if else in conditional testing? [duplicate] - cypress

This question already has answers here:
Cypress: How to know if element is visible or not in using If condition?
(3 answers)
Closed 23 days ago.
Hi have this code and i want to assert the $element if visible or not visible. How can i do it? i tried should and expect but its failing
cy.get('.cloudfront_new_header').then(($element) => {
if ($element.style.visibility = "hidden"){
cy.log('Visible')
} else {
cy.log('NotVisible')
}
})

You have to use the Jquery method is(':visible') for this.
cy.get('.cloudfront_new_header').then(($ele) => {
if ($ele.is(':visible')) {
cy.log('Visible')
} else {
cy.log('NotVisible')
}
})

Related

Cypress - How to use if statement with contains

so I have to use cy.contains to find the element I want, but all I can find online is how to use if() with cy.find or cy.get if there a way to do this with contains?
Example code:
if(cy.contains('div.name', 'Test 1').length > 0) {
//Type in name
cy.get('input.newName').click().type('Test 1');
cy.wait(2000);
//Click Add Name
cy.get('div.createNewName> a').click();
cy.wait(2000);
}
What I am trying to do there is:
if(Name doesnt exist){
Create it
}
I'm not sure if I have explained myself too well, if any more clarifications are needed feel free to ask
You can also do like this:
cy.get('body').then(($body) => {
if ($body.find('div.name:contains("Test 1")').length > 0) {
//Element Found
} else {
//Element not found
}
})
The general pattern for this would be as follows:
const element = Cypress.$('div.name:contains(Test 1)')
if (element.length > 0) {
...
Make sure the DOM is stable when you run this code, there is no retry built in as there is with cy.contains()
If the code inside if() is creating the name, then maybe the logic would be
const element = Cypress.$('div.name:contains(Test 1)')
if (element.length === 0) {
// not found so create it
...
You can also do it like this
cy.get('div.name').then($div => {
const found = $div.find(':contains("Test 1")')
if (found.length === 0) {
// create...
}
})

Cypress if else conditional test

I am trying to include the below condition into my test but I can't seem to get it to work and receive the below error, any ideas why?
Essentially, I want to test that a input is / is not empty:
cy.get(`[class^='input-module_field']`).eq(0).then(($input) => {
if ($input.should('have.value', '')) {
cy.get(`[class^='input-module_field']`).eq(0).should('be.visible').type(foo)
cy.get(`[class^='input-module_field']`).eq(1).should('be.visible').type(bar)
cy.get(`[class^='input-module_field']`).eq(2).should('be.visible').type(foo-bar)
cy.get(`[class^='input-module_field']`).eq(3).should('be.visible').type(foo-bar-foo)
} else {
cy.get(`[class^='input-module_field']`).eq(1).should('be.visible').type(bar)
cy.get(`[class^='input-module_field']`).eq(2).should('be.visible').type(foo-bar)
cy.get(`[class^='input-module_field']`).eq(3).should('be.visible').type(foo-bar-foo)
}
})
The error i get:
$input.should is not a function
When yielded from a .then(), the $input variable is just a JQuery element, and can't use Cypress commands. In this case, even using a Cypress command, such as .should() wouldn't work, because that does not yield a boolean value for the if/else.
Instead, we'll want to use JQuery's .val() function.
...
if ($input.val()) { // if $input.val() returns an empty string, this evaluates to false
// code to run if the $input element has a value
} else {
// code to run if the $input element does not have a value.
}
...
Note: I reversed the order of what you had, with the $input.val() === '' being the else, instead of the if.
The check can be on the value itself
cy.get(`[class^='input-module_field']`).eq(0)
.then(($input) => {
const field0Val = $input.val() || 'foo' // if empty use "foo"
cy.get(`[class^='input-module_field']`).eq(0).type(field0Val)
cy.get(`[class^='input-module_field']`).eq(1).type('bar')
cy.get(`[class^='input-module_field']`).eq(2).type('foo-bar')
cy.get(`[class^='input-module_field']`).eq(3).type('foo-bar-foo')
})

cypress: How can manage the application flow, if the element xpath is not present

I have the following scenario:
if the element is present, i have to do one activity and if not present will do another activity.
cy.xpath("//div[text()= 'button').its('length').then(res=> {
if (res > 0) {
return 1;
}
else {
cy.log ("Element is not present")
}
}
)} '''
if element is present = Code is working fine,
if the element xpath is not present = it try to search the element xpath (//div[text()= 'button') and throwing the error as 'Timed out retrying: Expected to find element: undefined, but never found it.'
if element is not present, Is there any way, i can handle the code ,
When using xpath you can (sort of) make it conditional by wrapping the xpath selector with count().
cy.xpath("count(//div[text()= 'button'])") // ok with async content
.then(count => {
if (count) {
//return 1; // not useful, returns a "chainer"
// ...but you can perform the required test here, e.g
cy.xpath("//div[text()= 'button']").click()
} else {
cy.log('not found')
}
})
The shorter syntax using built-in jQuery might be
const exists = !!Cypress.$("div:contains('button')").length
if (exists) {
cy.xpath("//div[text()= 'button']").click()
} else {
cy.log('not found')
}
Note that this is a partial match to 'button', where-as the xpath syntax is an exact match.
Also note - using Cypress.$ by-passes retry-ability, so it should not be used where the text is asynchronous.
From docs
This is a great way to synchronously query for elements when debugging from Developer Tools.
The implication is that it's more for debugging after the page has loaded.
The best practice is to try to construct the test and the app's data in such a way that you know that the button is present.
You can do something like this. With Cypress.$, you can validate the presence of the element with the help of the length attribute and then do further actions.
cy.get('body').then($body => {
const ele = $body.find('selector');
if (Cypress.$(ele).length == 0) {
//Do Something element is not present
}
else if (Cypress.$(ele).length > 0) {
//Do Something when element is present
}
})

Laravel Search Condition Problem. When condition is value empty, then go to else condition. But it's not work properly

This is my search code please see then solution, thank you.
You have to use like this
$report_ex = Expenses::where(condition)->where(condition)->get();
or
$report_ex = Expenses::where(condition)->where(condition)->first();
If you are using
$report_ex = Expenses::where(condition)->where(condition)->first();
then you need to call
if(!empty($report_ex))
{
// your code
}
else
{
//your code
}
But if you are using
$report_ex = Expenses::where(condition)->where(condition)->get();
then you should use
if(count($report_ex) > 0)
{
// your code
}
else
{
// your code
}
since get function returns an empty object

How to restrict a input field numeric in knockout js [duplicate]

This question already has answers here:
make an input only-numeric type on knockout
(10 answers)
Closed 8 years ago.
I have an input field and i want to restrict it only for numeric values. How can i do it in knockout js
here is my field
<input data-bind="value: nsc" />
You can write a function in your view model.
ko.extenders.numeric = function(target, precision) {
//create a writable computed observable to intercept writes to our observable
var result = ko.pureComputed({
read: target, //always return the original observables value
write: function(newValue) {
var current = target(),
roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
//only write if it changed
if (valueToWrite !== current) {
target(valueToWrite);
} else {
//if the rounded value is the same, but a different value was written, force a notification for the current field
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({ notify: 'always' });
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
Check this link how to use : Sample code
Guess this question is already answered.
You may need to create custom binding which accepts only allowed characters.
The answer to the post in this link will help you: make an input only-numeric type on knockout

Resources