Testing text of an element using Cypress - cypress

I'd like to validate the text of an element (p element, for instance) with the help of Cypress.
I have used this code:
cy.get('#word').should('have.value', 'Color')
and I received this:
expected <p#word> to have value Color, but the value was ''
Evidently, it validates the CSS but not the html element value. How can I validate the element content here?

If you are asserting the inner Text, instead of have.value you have to use have.text.
cy.get('#word').should('have.text', 'Color')
Or, If you want to assert a partial string, you can use include.text
cy.get('#word').should('include.text', 'Color')

Related

How to check either the headline or the content should contain "FIFA" keyword?

How do I write this test in Cypress?
enter image description here
I have to confirm that either the headline or paragraph should contain the same keyword.
It's better to have JQuery elements in hand before the assertion so that you can use JQuery methods on them. cy.get() acts just like $(...) in JQuery, it will be enough to have the elements. (more here)
Once u have the elements, i.e. $el1 and $el2 below, then you can get their text via .text() method (more here) and then you can write your assertion.
Instead of a separate assertion, below I used a single one and checked if either of them includes the desired text by using || operator.
cy.get('first-el').then($el1 => {
cy.get('second-el').then($el2 => {
const inEl1 = $el1.text().includes('FIFA');
const inEl2 = $el2.text().includes('FIFA');
expect(inEl1 || inEl2).to.be.true;
});
});

How to select elements with same ID but in different shadow DOMs

So I'm working at a co. as a summer intern and have been tasked with writing tests for their application in cypress.
The application extensively uses shadow DOMs and nested shadow DOMs even. I used the includeShadowDom property true to traverse more easily. But I am facing an issue.
I need to type in 2 input boxes having the same ID and same class but they are in separate shadows. Is there a way I can distinguish between them i.e First occurrence of element with id= and nth occurrence of element with id=?
I can't share any code because it goes against company policy
Assuming you have added includeShadowDom: true in your cypress config file then you can use the eq method to get the respective elements.
E.g. eq(0) for first occurrence of the element, eq(1) for the second and so on.
So your code should look like this:
cy.get('input').eq(0).type('some text')
First possible solution is to select every input with class = something and loop over each.
let words = ['First input', 'second input']
cy.get(`input[class="something"]) // this returns x number of Inputs
.each( ($el, index) => {
cy.get($el)
.type(words[index])
})
Second possible solution is to target the parent element incasing the single input.
cy.get('table') //I don't know what is incasing your inputs but lets assume its a table
.within( () => {
cy.get(`input[class="something"`] //trying to get this to return 1 element
.type('words')
})
Without seeing your HTML markup I can't offer up a more exact solutions. Hope this helps. Look up parent() and parentsUntil() cypress commands if you try the second option.
With inputs there's usually some text that allows the user to distinguish them.
Try targeting the input label or placeholder text, finding the input with "Traversal" commands.
<div>
<label>User name</label>
<input type="text" placeholder="Enter user name" />
<div>
Some basic approaches:
cy.contains('label', 'User name')
.next() // move to next element in the DOM
.type('something')
cy.contains('div', 'User name') // go to common parent of label and input
.find('input') // gives just the input inside parent
.type('something')
cy.get('input[placeholder="Enter user name"]') // use unique placeholder attribute
.type('something')
With shadow DOM be aware you can configure it in the test header
it('searches inside all shadow dom roots', {includeShadowDom: true}, () => {
...
})

How to query data-attribute for a whitespace-separated value in Cypress component tests?

When testing a complex component, I want to assign multiple whitespace-separated values to data-cy attribute, for example
<div data-cy="my-component disabled" />
and use the ~= attribute selector to query for the element:
cy.get('[data-cy~="my-component"]')
Now, having already queried for my-component, how can I further assert that it:
does contain "disabled" in data-cy
does not contain "disabled" in data-cy
in broader sense, does or does not satisfy a css selector?
I know I can explicitly re-query with all parameters for each assertion, eg.:
cy.get('[data-cy~="my-component"]:not([data-cy~="disabled"])').should('exist')
but this feels overly complicated and doesn't read very well - I want to query the element first, and further assert against it in a later step - for example:
cy.get('...').should(el => {
// assert here
})
The approach seems like a good one. If you used individual attributes, likely they would clash with other "native" attributes.
For example if data-cy="disabled" means the "Person" has a disability, but used unwrapped the browser would disable the element.
Ref Using data attributes
data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.
Also some frameworks (React) are fussy about the attributes allowed on an element.
You might be looking for a function to provide the selector for the test.
const asDataCy = (attrs) => {
return attrs.split(' ').map(attr => {
let op = '~'
if (item.charAt(0) === '!') {
op = '!'
attr = attr.slice(1)
}
return `[data-cy${op}="${attr}"]`
).join('')
}
cy.get(asDataCy('my-component !disabled'))
// [data-cy~="my-component"][data-cy!="disabled"])
The Chai-jQuery assertion expect($el).match(selector) does exactly that!
// should form
cy.get('[data-cy~="my-component"]')
.should('match', '[data-cy~="some-value"]')
.should('match', ':not([data-cy~="something-else"])')
// expect form
cy.get('[data-cy~="my-component"]')
.then(el => expect(el).to.match('[data-cy~="some-value"]'))
.then(el => expect(el).to.match(':not([data-cy~="something-else"])'))

How to take xpath to Get Text from class inside th

I have the following XPath :
//table[#class='ui-jqgrid-htable']/thead/tr/th//text()
And I'm trying to get the text from it with the following command :
String LabelName = driver.findElement(By.xpath("//table[#class='ui-jqgrid htable']/thead/tr/th//text()")).getText()
But it's not printing text, the result is blank. Could you help me please ?
The text() in your xpath does not qualify as an element. Your element ends at //table[#class='ui-jqgrid-htable']/thead/tr/th. Try using getText() for this XPath.
Also, a table would have many headers. Using findElement will only return the first one.
If you want to get all headers use
driver.findElements(By.xpath("//table[#class='ui-jqgrid-htable']/thead/tr/th"))
and loop through the list to getText of individual element.

getting the value of text field using rspec selenium

How do we use selenium webdriver + ruby to check to see if the value of a text field is equal to a certain value?
I was doing:
#tester.browser.find_element(:id => "id_of_text_field").text.should == 'test value'
Why doesn't that work?
this test failed ... couldn't get the value of the text field.
Text fields do not have text. The value you see in the text field is actually the value of their value attribute.
You can get an element's value attribute by doing:
element['value']
Therefore, your test needs to do:
#tester.browser.find_element(:id => "id_of_text_field")['value'].should == 'test value'
Write as below using should eql(expected)
Passes if given and expected are of equal value, but not necessarily the same object.
# I write in below way, just for readability, you can write it in one line.
elem = #tester.browser.find_element(:id => "id_of_text_field")
elem.text.should eql('test value')

Resources