Testcafe Wait until an element has a specific text - testing

After uploading an image with TestCafe the server will do some processing. While this time a label on the website will have "Inprogress" as a label. After the server is ready it will change to date. However, I want to tell the Testcafe script to wait until the label is not "Inporgress" anymore.
For this I did:
const DeliveryStatus = {
element: Selector('div.cl-asset-published').with({timeout: 70000}),
delivered: 'Inprogress'
};
And in the script I have
await t
.expect(DeliveryStatus.element).notContains(DeliveryStatus.delivered, { timeout: 70000 })
But this step fails. The message I got is "AssertionError: object tested must be an array, a map, an object, a set, a string, or a weakset, but function given" but I do not have any idea why.
Any suggestion to fix this issue?

You pass an element selector that returns the element but not a string to the expect function. Try using the element's innerText property instead as follows:
await t
.expect(DeliveryStatus.element.innerText)
.notContains(DeliveryStatus.delivered, { timeout: 70000 })

Related

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

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

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)

Capybara, Poltergeist, PhantomJS, evaluate_script, callback

I am using the following code, which uses the imagesLoaded package with a callback to tell me when an element with a particular csspath has finished loading all of its images:
imagesLoadedScript = "imagesLoaded( '#{csspath}', { background: true }, function(message) { console.log('PHANTOM CLIENT REPORTING: #{csspath} Images Loaded'); return message; })"
imagesLoadedScript = imagesLoadedScript.strip.gsub(/\s+/,' ')
#session.evaluate_script(imagesLoadedScript)
The timing of the console.log statement, on inspection of PhantomJS logs with debug on, indicates that Capybara/Poltergiest is not waiting for the images to load, as expected, before it moves on to the next statement. I also cannot return a true (or false) value from inside the callback as I would like.
Capybara responds with
{"command_id":"678f1e2e-4820-4631-8cd6-413ce6f4b66f","response":"(cyclic structure)"}
Anyone have any ideas on how to return a value from inside a callback in a function executed via evaluate_script?
Many thanks.
TLDR; You can't
evaluate_script doesn't support asynchronous functions - you must return the result you want from the function passed in. One way to do what you want would be to execute the imagesLoaded script and have the callback set a global variable, and then loop on an evaluate_script fetching the result of the global until it's what you want - A very basic implementation would be something like
imagesLoadedScript = "window.allImagesLoaded = false; imagesLoaded( '#{csspath}', { background: true }, function() { window.my_images_loaded = true })"
#session.execute_script(imagesLoadedScript)
while !#session.evaluate_script('window.allImagesLoaded')
sleep 0.05
end
Obviously this could be made more flexible with a timeout ability, etc.
A second option would to write a custom capybara selector type for images with a loaded filter, although with the need for background image checking it would become pretty complicated and probably too slow to be useful.
Just in case someone finds this later.
I did roughly what Thomas Walpole suggested in his answer, in a more roundabout fashion, but taking advantage of Poltergeist's inherent waiting capabilities;
#to check that the target has loaded its images, run images loaded
#after a small timeout to allow the page to get the images
#append a marker div to the dom if the images have successfully loaded
imagesLoadedScript = "var item = document.querySelector('#{csspath}');
window.scroll(0, item.offsetTop);
function imagesDone(path, fn) {
imagesLoaded( path, function(instance) {
console.log('PHANTOM CLIENT REPORTING: ' + path + ' Images Loaded');
fn(true);
})
}
setTimeout(function(){
imagesDone('#{csspath}', function(done) {
var markerDiv = document.createElement('div');
markerDiv.id = 'ImagesLoadedMarker';
document.getElementsByTagName('html')[0].appendChild(markerDiv);
});
}, 1000)"
#then we strip the new lines and spaces that we added to make it readable
imagesLoadedScript = imagesLoadedScript.strip.gsub(/\s+/,' ')
#now we just execute the script as we do not need a return value
#session.execute_script(imagesLoadedScript)
#then we check for the marker, using capybara's inbuilt waiting time
if #session.has_xpath? "//*[#id ='ImagesLoadedMarker']"
Rails.logger.debug "!!!!! PhantomClient: Images Loaded Reporting: #{csspath} Images Loaded: Check Time #{Time.now} !!!!!"
#session.save_screenshot(file_path, :selector => csspath)
else
Rails.logger.debug "!!!!! PhantomClient: Images Loaded Reporting: #{csspath} Images NOT Loaded: Check Time #{Time.now} !!!!!"
#session.save_screenshot(file_path, :selector => csspath)
end

Vue 2 About nextTick

I have read that nextTick allows codes to be executed at the next action. But this does not work in my code, can someone helps me on this? Please correct me. Thanks.
.vue
.....
methods:{
getUserInfo(){
var vm = this
vm.$http.get('/getAuthUser').then((response)=>{
vm.user = response.data
})
Vue.nextTick(()=>{
vm.$http.get('/getShop/'+vm.user.id).then((response)=>{
vm.shop = response.data.data.shop
})
})
},
}
.....
{{user.id}} does work. where this gives me the following error:
GET http://localhost:8000/getShop/undefined 404 (Not Found)
EDIT#1
if i do something like this it works but this should not be the right way to do in my opinion.
.....
methods:{
getUserInfo(){
var vm = this
vm.$http.get('/getAuthUser').then((response)=>{
vm.user = response.data
vm.$http.get('/getShop/'+vm.user.id).then((response)=>{
vm.shop = response.data.data.shop
})
})
},
}
.....
EDIT#2
If I do something like this it wont work coz vm.user.id is not set.
.....
methods:{
getUserInfo(){
var vm = this
vm.$http.get('/getAuthUser').then((response)=>{
vm.user = response.data
})
vm.$http.get('/getShop/'+vm.user.id).then((response)=>{
vm.shop = response.data.data.shop
})
},
}
.....
I think your understanding of what nextTick does is incorrect. If you read the documentation, it says that the callback you pass to the nextTick function will be executed after the next DOM update.
Let's say you have a property that determines whether an element exists or not in the DOM with a v-if directive. If you change the value of the property so that the element exists in the DOM, you might have to wait for Vue to process the change and update the DOM before you can grab a reference of that element, for example. In that case, you should use Vue.nextTick to make sure by the time you want to query the DOM to get that element, it actually exists.
Your scenario doesn't have anything to do with the DOM.
You have 2 asynchronous HTTP calls that you want to execute one after another, because the second relies on the result of the first. Your original implementation and third one (EDIT#2) are flaky because you don't make sure the first HTTP request is complete before firing the second one, which explains why you get errors about vm.user.id not being set.
Your second implementation (EDIT#1) is more correct because the second HTTP request is fired after the first one completes. Still, I'd suggest a minor modification:
getUserInfo() {
vm.$http.get('/getAuthUser')
.then(response => {
vm.user = response.data;
return vm.$http.get('/getShop/' + vm.user.id);
}).then(response => {
vm.shop = response.data.data.shop;
});
}
The first callback returns a Promise which result is fed into the second then call. I like this approach because it avois having nested thens. I would also suggest you to read the MDN docs on Promises.

How do you poll for a condition in Intern / Leadfoot (not browser / client side)?

I'm trying to verify that an account was created successfully, but after clicking the submit button, I need to wait until the next page has loaded and verify that the user ended up at the correct URL.
I'm using pollUntil to check the URL client side, but that results in Detected a page unload event; script execution does not work across page loads. in Safari at least. I can add a sleep, but I was wondering if there is a better way.
Questions:
How can you poll on something like this.remote.getCurrentUrl()? Basically I want to do something like this.remote.waitForCurrentUrlToEqual(...), but I'm also curious how to poll on anything from Selenium commands vs using pollUntil which executes code in the remote browser.
I'm checking to see if the user ended up at a protected URL after logging in here. Is there a better way to check this besides polling?
Best practices: do I need to make an assertion with Chai or is it even possible when I'm polling and waiting for stuff as my test? For example, in this case, I'm just trying to poll to make sure we ended up at the right URL within 30 seconds and I don't have an explicit assertion. I'm just assuming the test will fail, but it won't say why. If the best practice is to make an assertion here, how would I do it here or any time I'm using wait?
Here's an example of my code:
'create new account': function() {
return this.remote
// Hidden: populate all account details
.findByClassName('nextButton')
.click()
.end()
.then(pollUntil('return location.pathname === "/protected-page" ? true : null', [], 30000));
}
The pollUntil helper works by running an asynchronous script in the browser to check a condition, so it's not going to work across page loads (because the script disappears when a page loads). One way to poll the current remote URL would be to write a poller that would run as part of your functional test, something like (untested):
function pollUrl(remote, targetUrl, timeout) {
return function () {
var dfd = new Deferred();
var endTime = Number(new Date()) + timeout;
(function poll() {
remote.getCurrentUrl().then(function (url) {
if (url === targetUrl) {
dfd.resolve();
}
else if (Number(new Date()) < endTime) {
setTimeout(poll, 500);
}
else {
var error = new Error('timed out; final url is ' + url);
dfd.reject(error);
}
});
})();
return dfd.promise;
}
}
You could call it as:
.then(pollUrl(this.remote, '/protected-page', 30000))
When you're using something like pollUntil, there's no need (or place) to make an assertion. However, with your own polling function you could have it reject its promise with an informative error.