cy.type stop mid-typing, finishes after .wait - cypress

I'm seeing an issue where cypress (v6.9.1) is randomly stopping mid-type, despite the fact that no other events are triggering on our page, and continuing after a .wait as it proceeds to execute other commands.
cy.get(`[placeholder="Search"]`)
.clear()
.click()
.type(search) //types a portion of 'search', then stops
.wait(500);
//continues typing the rest of search
This issue is sporadic and can not be reliable reproduced, and can and has happened on any text input on our app. Any ideas on what could be causing it?

You can add a delay while typing something like below. Now each keypress will be delayed 50ms.
cy.get('[placeholder="Search"]').clear().click().type(search, {delay: 50})

When using a component like React Async Select and wanna select an option you can do.
cy.get("#elementid").type("Jef{enter}", { delay: 100 });
so each consecutive keystroke, it will wait 100 ms. Not the greatest solution as it's arbitrary.
I haven't found a better solution using cy.intercept so if anyone has one, please let me know.

Related

How do I save Cypress's testrunner's "console log" (left hand side) to a file

I would like to save the data from the left-hand-side of the TestRunner to a text file (json, plain text, or any kind of text).
I feel like this should be very easy, and that I'm simply just missing something. However, I cannot find anything to explain this. I have checked this other S.O. question: Cypress pipe console.log and command log to output, which references this currently open issue -- but this appears to be focused on collecting the browsers console log.
I even tried one of the workarounds suggested in the discussion of that open issue, cypress-log-to-output - but that put a ton of output in the terminal from which I launched the test. I did try to correlate the extra output to the relatively few entries from the TestRunner's left-hand-side, but did not see anything to match them up.
I'm just hoping to get a text file that looks like this (with perhaps a bit of detail for each entry):
1 visit /
(xhr) GET 200 /todos
2 wait #todos
(req) GET /todos Received todos
...
Or perhaps JSON.
My motivation comes from having to write Cypress tests for our CI that will be testing a very old AjaxSwing based application that makes heavy use of XHR requests, and it can be a different number of XHR requests for each test run (sometimes 8, sometimes 12 just to load the first page).
The AjaxSwing app is not changing, so I have to figure this out as best as possible. So I wanted to see a whole text file with all the information from the TestRunner's left hand side. Perhaps even compare separate runs to see if I can spot some "header" or "body" value I could use to distinguish the right XHR request to wait for.
Any help would be appreciated.
One approach using the log:added event
// top of spec
const logs = []
Cypress.on('log:added', (log) => {
const message = `${log.consoleProps.Command}: ${log.message}`
logs.push(message)
})
it('writes to logs', () => {
... // some commands that log
cy.writeFile('logs.txt', logs)
});

Cypress retries making test always pass

I am attempting to use the Cypress (at 7.6.0) retries feature as per https://docs.cypress.io/guides/guides/test-retries#How-It-Works
but for some reason it seems to be not working, in that a test that is guaranteed to always fail:
describe('Deliberate fail', function() {
it('Make an assertion that will fail', function() {
expect(true).to.be.false;
});
});
When run from the command line with the config retries set to 1,
npx cypress run --config retries=1 --env server_url=http://localhost:3011 -s cypress/integration/tmp/deliberate_fail.js
it seems to pass, with the only hint that something is being retried being the text "Attempt 1 of 2" and the fact that a screenshot has been made:
The stats on the run look also to be illogical:
1 test
0 passing
0 failing
1 skipped (but does not appear as skipped in summary)
Exactly the same behavior when putting the "retries" option in cypress.json, whether as a single number or options for runMode or openMode.
And in "open" mode, the test does not retry but just fails.
I am guessing that I'm doing something face-palmingly wrong, but what?
I think your problem is that you are not testing anything. Cypress will retry operations that involve the DOM, because the DOM takes time to render. Retrying is more efficient than a straight wait, because it might happen quicker.
So I reckon because you are just comparing 2 literal values, true and false, Cypress says, "Hey, there is nothing to retry here, these two values are never going to change, I'm outta here!"
I was going to say, if you set up a similar test with a DOM element, it might behave as you are expecting, but in fact it will also stop after the first attempt, because when it finds the DOM element, it will stop retrying. The purpose of the retry is to allow the element to be instantiated rather than retrying because the value might be different.
I will admit that I could be wrong in this, but I have definitely convinced myself - what do you think?
Found the cause .. to fix the problem that Cypress does not abort a spec file when one of the test steps (the it() steps) fails, I had the workaround for this very old issue https://github.com/cypress-io/cypress/issues/518 implemented
//
// Prevent it just running on if a step fails
// https://github.com/cypress-io/cypress/issues/518
//
afterEach(function() {
if (this.currentTest.state === 'failed') {
Cypress.runner.stop()
}
});
This means that a describe() will stop on fail, but does not play well with the retry apparently.
My real wished-for use case is to retry at the describe() level, but that may ne expensive as the above issue just got resolved but the solution is only available to those on the Business plan at $300/mo. https://github.com/cypress-io/cypress/issues/518#issuecomment-809514077

Cypress not retrying assertion

My Cypress test is acting inconsistently due to an assertion set on header text. Here is my code:
cy.get('.heading-large').should('contain', 'dashboard') // passes
cy.contains('View details').first().click()
cy.get('.heading-large').should('contain', 'Registration details') // sometimes fails
If it fails, it is because the heading still contains 'dashboard' - Cypress appears not to have retried but gives error Timed out retrying: expected '<h1.heading-large>' to contain 'Registration details'
From reading about Cypress retry-ability, my understanding is that the should assertion should keep trying until timeout, which is set as "defaultCommandTimeout" : 5000. This feels true even if I have an element with the same identifier across two pages. There are no major performance issues with the app I'm testing.
The test seems more likely to fail if I am not watching the window and this issue looks like a possible cause.
Can anyone help determine: is there an issue with my test or Cypress, and how might I improve the test? I'm using Cypress 5.1.0 and Chrome 85 on MacOS Catalina.
It is failing occasionally because the request that fills the header with information has not resolved by the time the timeout has been reached.
You can solve this by setting up a route with a route alias to wait for that exact response from the request to resolve before you proceed with the click.
In other words, When you click(), there is a request sent that grabs the information you want to check for in the next get(). This response for this request has sometimes not resolved by the time your get() reaches timeout. You could increase the timeout but that's not recommended and not good practice here. Instead, wait for that specific response with route & route alias. If you do that, in every case, the last get() won't get called until the information it is looking for has been resolved.
I don't know your request but it would work something like this:
// setup the route and alias
cy.server()
cy.route("/youRequestUrlHere").as("myLovelyAlias")
// first get
cy.get('.heading-large').should('contain', 'dashboard')
// this click fires the request url from route() above
cy.contains('View details').first().click()
// wait for route to resolve using route alias
cy.wait("#myLovelyAlias").then((response) => {
// next get called after response resolves
cy.get('.heading-large').should('contain', 'Registration details')
}
Reference:
Route & alias
Route
Best Practice - get()
Network Request - wait()
edit:
As mentioned above, you could also cheat and set the defaultCommandTimeout to a higher number but that is not recommended because you could still run into cases where the response resolution takes longer than the timeout you've set. The route/wait pattern is the better, more stable approach.
Just in case you want to know how its done though, you would change your get() to something like:
cy.get('.heading-large', {defaultCommandTimeout: 60000}).should('contain', 'Registration details')
Again, other way would be much better.
Reference:
Cypress configuration
It looks like we need to wait for the Cypress bug "Some tests flake only if test runner's browser loses focus (or run headlessly)" to be fixed. This is because I have tried the alternative, helpful answers but am consistently facing the original issue when the window is out of focus.
Thank you to those who have answered and commented.

watir/ruby waiting for iframe to exist

I have a problem waiting for an iframe to exist on page after entering a date range and I would rather not use sleep. I am using ruby/watir
I have tried solutions like this -
wait_until(10, "iFrame has not loaded") do
#browser.iframe(id: "dtl00_DP1_content").exists?
end
but this simply returns this error - Selenium::WebDriver::Error::NoSuchWindowError: no such window
So how do I wait for an iframe that does not yet exist please?
I am not sure whether you only want to wait for an Iframe, If you want to perform any operation on an element which is present in the iframe, then you could do as I mentioned in my comment.
#browser.iframe(name: "something").text_field(name: "username").set 'raja'
Or If you still wait for an iframe to appear, then write the following code
#browser.wait_until { #browser.iframe(id: "dtl00_DP1_content").exists? }
The above code waits for 30 seconds, but If you want to increase the time to wait, then write the following code, the following code would wait fo 50 seconds.
#browser.wait_until(timeout: 50) { #browser.iframe(id: "dtl00_DP1_content").exists? }

How to wait until the embedded ajax call is completed when injecting my script?

It's Google Chrome extension development. I'm using content script to inject into webpages. However some webpages have their own ajax scripts that change the content dynamically. How do I wait until such scripts are completed, since before their completion my script cannot obtain the correct content?
For example,
1- on Google search result page,
2- I want to append "text" to title of every search result item, which could be easily done by calling,
$('h3').append("text");
3- then listen to the search query change, done by
$('input[name="q"]').change( function(eventObj){
console.log("query changed");
// DOESN'T work
$('h3').append("text");
});
The last line doesn't work probably because at the time it's executed the page is still refreshing and $('h3') is not available. Google uses ajax to refresh the search result when the query is changed on the page.
So the question is how to capture this change and still be able to append "text" every time successfully?
EDIT:
Have tried and didn't work either:
$('h3[class="r"]').delay(1000).append("text");
and using .delay() is not really preferred.
EDIT:
.delay() is simply not designed to solve pause the execution of scripts other than UI effects. An workaround is
$('input[name="q"]').change(function(eventObj) {
setTimeout(function() {
$('h3[class="r"]').append(" text");
}, 1000);
});
But as I argued before, setTimeout() is connection-speed dependent, not preferred because I have to manually balance the time of waiting and the speed of response (of my script).
Although this post is down-voted for god-knows-why I'll still be waiting for an elegant answer.
Maybe with jQuery 1.7+ (or with older version using "live" or "delegate")
$('form').on( "change", 'input[name="q"]', function(eventObj){
console.log("query changed");
$('h3').append("text");
});
If form is another element, change it accordingly.

Resources