In Testcafe, how can I wait for a 2nd element of the same selector to appear? - testing

I have a scenario in which multiple elements of the same className appear one after the other (it depends on a server response).
What I'm trying to achieve is passing the test only after 2 elements of the same selector are present, but currently, it seems like the test fails because it keeps recognizing 1 element and then straight up fails without waiting for a 2nd one.
This is my code (called from the outside with a count argument of, say, 2) -
import { Selector } from 'testcafe';
export const validateMsg = async (t, headlineText, count = 1) => {
const msgHeadline = Selector('.myClassName').withText(headlineText).exists;
const msgHeadLineExists = await t
.expect(msgHeadline.count)
.gte(count, `Received less than ${count} desired messages with headline ${headlineText}`);
return msgHeadLineExists;
};
I assume this happens because I'm checking whether msgHeadline exists, and it sees the first element when it gets rendered, and immediately fails. I'd like to wait for a 2nd one.
Any ideas?

Just remove the .exists from your selector it returns boolean and then calling .count on it will fail the test.
const msgHeadline = Selector('.myClassName').withText(headlineText);
const msgHeadLineExists = await t
.expect(msgHeadline.count)
.gte(count, `Received less than ${count} desired messages with headline ${headlineText}`);
return msgHeadLineExists;
You can read more here
https://devexpress.github.io/testcafe/documentation/test-api/selecting-page-elements/selectors/using-selectors.html#check-if-an-element-exists

If both elements have same text and only this elements have this specific className then you can use nth() function
const msgHeadline = Selector('.myClassName')..withText(headlineText).nth(1);
await t
.expect(msgHeadline.exists).ok(`Received less than ${count} desired messages with headline ${headlineText}`)
Here you take second element with headlineText and then assert, that it exists. Though i think you should check that it exists and displayed(visible)

Related

How to get all <a> tag under the <div> in testcafe

In selenium query for selector, if my selector value was (#div-id a). It return all a tags.
Does in testcafe is it posible this to selector function? i just want to avoid looping to get all a tags.
Code Sample
const element = selector('#div-id').find()
var get = await brandUrls.hasAttribute();
console.log(get);
Actual element attached
Yes, it is also possible to achieve the desired behavior with TestCafè in a similar way:
import { Selector } from "testcafe";
// one option
const firstLinkSelector = Selector("#directoryLink-1 a");
// another option
const secondLinkSelector = Selector("#directoryLink-1").find("a");
Read more about the find()-method here.

How to get cypress to return children length of 0 when there isnt any children

So I am writing a test that will add a card to a container(payment-card-container) and I want to confirm an element was added later by seeing if the children have increased by 1. But I am having issues when we try to count the children length when there isnt any. I am currently using the below:
cy.get('[data-test-id="payment-card-container"]')
.children()
.its('length')
.then(length => {
const childrenLength = length;
})
But Cypress seems to get an error because it cant find the children (Error below).
Timed out retrying: Expected to find element: ``, but never found it.
Is there a way this can work when there isnt any children and it returns the value of 0?
The problem with using a jQuery expression like
Cypress.$('[data-test-id="payment-card-container"]').children().length
is you don't get the Cypress retry for async updates.
If adding a payment card calls an API, the above expression will falsely report 0 children instead of waiting for the DOM to update.
There's really no good way to handle the no-cards situation,
Except
set up your test scenario such that there are no cards initially
add a card
confirm that there is now exactly one card
If you must test for zero children, a trailing .should() will remove the error message.
cy.get('[data-test-id="payment-card-container"]')
.children()
.should('have.length', 0); // no error when should expression passes
// Add card here
cy.get('[data-test-id="payment-card-container"]')
.children()
.should('have.length', 1); // waits for async add-card operation
Tested with
<body>
<div data-test-id="payment-card-container"></div>
<script>
setTimeout(() => {
const div = document.querySelector('[data-test-id="payment-card-container"]');
const p = document.createElement('p')
div.appendChild(p)
}, 2000)
</script>
</body>
One hacky way that I could think of is this. You can use the jQuery length and children() property to check the length:
cy.get('body').then(() = > {
if (Cypress.$('[data-test-id="payment-card-container"]').children().length == 0) {
//Do Something
}
else {
//Do Something
}
})

Testcafe .parent() of Selector sporadically fails before timeout

I have a TestCafe test that checks if a Selector's parent exists and somehow it fails every other time. Here's the relevant code:
logWithTimestamp("Starts..."); // Prints "[2020-12-23T12:02:04.476Z] Starts..."
let state = await Selector('#indberetningsflow-knap-trin-stamdata', {timeout: 30000}).parent().exists;
logWithTimestamp(`State: ${state}`); // Prints "[2020-12-23T12:02:04.618Z] State: false"
await t.expect(state).ok() // Sometimes fails
As you can see, it fails after less than 200ms, even though the timeout is set explicitly to 30000. Now, I have an idea that maybe it fails when the selector is found, but the parent is not yet loaded. If this is true, why does TestCafe not wait for the parent to appear, and what can I do about it?
EDIT
I performed another experiment, and either there is something wrong with TestCafe or I have not understood something fundamental, but how can this fail after just 30ms?
logMedTidsstempel("Starts..."); // Prints "[2020-12-23T12:42:15.041Z] Starts..."
let state = await Selector('#indberetningsflow-knap-trin-stamdata', {timeout: 30000}).exists;
logMedTidsstempel("Found child."); // Prints "[2020-12-23T12:42:15.072Z] Found child."
await t.expect(state).ok(); // <- fails :(
To make your code example work, do the following:
Remove the await keyword from Selector
Remove the timeout option from Selector and pass it to the assertion method
...
let state = Selector('#indberetningsflow-knap-trin-stamdata').exists;
await t.expect(state).ok({timeout: 30000});
...
You may also wish to refer to the following help topic: https://devexpress.github.io/testcafe/documentation/guides/basic-guides/select-page-elements.html#selector-timeout

Webdriver.io browser.getText() sometimes returns undefined

I have this piece of code:
getText: (selector) => {
browser.waitUntil(function () {
return browser.isExisting(selector) === true;
},timeout,
'Could not find element after: ' + timeout,
pollingTime);
return browser.getText(selector);
}
And sometimes this function (getText(selector), but in deep browser.getText(selector)) returns undefined for the selector that looks like this:
article[data-product-id="test-00020"] li.product-entry__summary__item.is-price span
This doesn't happen every time test is run, but it happens occasionally. It is driving me nuts because the behavior is inconsistent. Sometimes it works and sometimes it doesn't.
Did anybody have similar problems? Please help! Thank you.
getText is dependent on the element being visible in the viewport of the page (so if it's scrolled off the page it will return an empty string)
Instead, you can use getHTML(false) to get the text content of an element (just ensure it's the inner-most element, otherwise you'll get HTML elements in the returned content)
If you use getHTML which I also did, you can strip out the HTML tags if they are not innerHTML:
var strArray = browser.getHTML("//div[myxpath]");
for(var i =0; i<strArray.length; i++){
strArray[i]=strArray[i].replace(/(<([^>]+)>)/ig, "");
strArray[i] = strArray[i].trim();
}
sorry for the Hungarian notation.

React Native - Saving search terms after delay

I am creating a search toolbar that allows the user to see their most recent searches, using Realm Browser as my database. I save a search whenever the user types in the TextInput component, however, I don't want to add a search term after each key stroke, but only after the user has stopped typing for certain amount of time.
handleOnChange function will update state and only call getResults after 2 seconds
handleOnChange(text) {
this.setState({
searchStr: text
}, () => setTimeout(() => {
this.getResults()
}, 2000))
}
In getResults, I call my addRecentSearch function if certain criteria is met.
getResults() {
let searchTags = []
let searchCalcs = []
let tagNames = this.state.tags.map((tag) => {
return tag.name
})
if (this.state.searchStr.length >= 2 || this.state.tags.length !== 0) {
searchCalcs = Realm.searchCalcs(this.state.searchStr, tagNames)
Realm.addRecentSearch(this.state.searchStr)
}
this.setState({
results: searchCalcs,
tagsForFiltering: searchTags
})
}
So I use setTimeout to allow enough time for my state to get updated when the user types. Then, once the states been updated, I will want to add the search query. However, I'm not getting the results I expected when grabbing the most recent searches.
For example:
Type: "h"
Result: nothing happens as str must be at least 2 characters in length
Type: "he"
Result: meets criteria, and will add "he" as a recent search term.
Arr: ["he"]
Type: "heart" (Note: adding 3 characters in succession)
Result: It seems that even with the timeout function, my getResults function is being called (thus adding the search query for each character I added)
Arr: ["he", "heart", "heart", "heart"]
I want my arr to look like:
arr: ["he", "heart"]
You aren't fully debouncing in your example. You are only delaying everything by 2000ms. You need to create a timer and then reset it every time a change happens (by clearing and starting timer again). In this way, only the final 'delay' takes effect. Make sense?
You are very close to have written your own debounce function, so you can use clearTimeout, or there are some libraries that do it. See Lodash https://lodash.com/docs/#debounce