Cypress 400 xhr error when clicking on a button - cypress

I have a button which will redirect to the application upon clicking it.
But when my automation script runs, it is always throwing POST 400 error.
I tried manually in my browser, and there is no error in the network tab. And also if you use Cypress to open the browser and load the application, there is no error.
I saw a similar one [here][1] but does not seem to solve my issue.
Test.js file :
describe ('Test', function()
{
it('Login', function(){
cy.url().should('include', '<url goes here>');
cy.wait(3000)
cy.get('h1').should('have.text', "WELCOME")
cy.get('button').contains("submit").click() ////executed till here. POST 400 error after this
})
}
)
HTML code :
<button class="MuiButtonBase-root MuiButton-root MuiButton-contained" tabindex="0" type="button">
<span class="MuiButton-label"> submit</span>
Error after running automation code :
(xhr) POST 400 : <api-url>
This is the response on the network tab => Failed to load response data : No resource with given identifier found.

Can you try to add failOnStatusCode:false, into your cy.request?
You can read more here: cypress documentation

Related

Cypress Javascript Automation: Getting 500 error when uploading using Cypress

I am trying to automate uploading a picture on a website. I can manually upload fine. But when I do it using Cypress and node module cypress-file-upload, I get 500 server error.
I have import 'cypress-file-upload'; in commands.js file. I have
Cypress.on('uncaught:exception', (err, runnable) => {
return false;
});
I get application threw an error if I do not have this exception code.
This is what my code looks like for upload
cy.fixture('settings.JPG').then(fileContent => {
cy.get('[id="xyz"]').attachFile({
fileContent: fileContent.toString(),
fileName: 'settings.JPG',
mimeType: 'image/png'
});
});
As I look at browser where cypress is running, I can see, file is being attached near the Choose file field. But as soon Cypress clicks on the submit button, it throws 500 error
If I go to Cypress view pane and click on the submit button, it throws 500 error again
But if I click on the choose file and select the same file and then click on Submit button, then I do not get 500 error and it works.
Can anyone point out why I am getting 500 error? and what can I do to get past this? Thanks a bunch in advance.
Try to replace your mimeType as a image/jpg.

Getting error while trying to upload a file in cypress

I am trying to automate file uploading via cypress but getting the error below.
I am not finding the root cause of the issue.
enter code here
The following error originated from your application code, not from Cypress.
Script error.
Cypress detected that an uncaught error was thrown from a cross origin script.
We cannot provide you the stack trace, line number, or file where this error occurred.
Check your Developer Tools Console for the actual error - it should be printed there.
It's possible to enable debugging these scripts by adding the crossorigin attribute and
setting a CORS header.
When Cypress detects uncaught errors originating from your application it will automatically
fail the current test.
This behavior is configurable, and you can choose to turn this off by listening to the
uncaught:exception event
Below is my code
it('Single File Upload-DOM', () => {
cy.visit('http://127.0.0.1:5500/Help%20Folder/fileupload.html')
cy.get('#file-upload1').attachFile('dog_small.jpg')
cy.get('span#fileName1').should('have.text','dog_small.jpg')
});
You can turn off the exception check globally by writing:
Cypress.on('uncaught:exception', (err, runnable) => {
return false
})
under cypress/support/index.js

Cypress truncates the URL after login

I have a simple login test in cypress (5.6.0, Windows 10). The application I am testing is written in PHP/MySQL. When I run the test in Cypress I get a 404 page not found error following the login.
This does not happen manually or with webdriver, just with Cypress.
Here is the script (which you can try)
describe('Admin Login', () => {
Cypress.config('baseUrl','https://www.edgewordstraining.co.uk/webdriver2')
it.only('Successful Login', () => {
cy.visit ('/')
cy.get('div#right-column > h1').contains('Web Testing Index Page V2 Sprint2')
cy.contains('Login').click()
cy.get('body').contains('User is not Logged in').should('exist')
cy.get('#username').clear()
cy.get('#username').type('edgewords')
cy.get('#password').clear()
cy.get('#password').type('edgewords123')
cy.contains('Submit').click()
//error 404 occurs here
//cy.visit ('/sdocs/add_record.php') //Had to add this as Cypress changes the URL from the form submit for some reason!
cy.get('body').contains('User is Logged in').should('exist')
//Logout
cy.contains('Log Out').click()
//Handle the confirmation Alert
cy.on('window:confirm',(str)=>{
expect(str).to.equal('Do You Really want to Exit the Secure site! Press ok to Continue ')
})
cy.get('body').contains('User was Logged in').should('exist')
});
And when I run with Chrome or Firefox, I get this in the log:
enter image description here
and in the Test Runner, the URL has been truncated:
enter image description here
The URL should be https://www.edgewordstraining.co.uk/webdriver2/sdocs/add_record.php,
but cypress changes it to https://www.edgewordstraining.co.uk/sdocs/add_record.php
webdriver2 is just a physical folder on the web server where this app/site is stored.
I see that someone else had a similar issue, but there are no replies on his question. Could anyone help? Thanks
Since the above post, I have now looked at the login function in the application itself.
else {
// document.write(response);
//location.replace("../sdocs/add_record.php");
//Had to change the line below as in Cypress, it is not moving back to the previous directory
//so have made it an absolute url instead
//window.location.href = "../sdocs/add_record.php";
window.location.href = "https://www.edgewordstraining.co.uk/webdriver2/sdocs/add_record.php";
return false;
}
The relative url path above should just go back to the parent directory (webdriver2) which it does if you use the site manually.
However, I have had to fix this as a fully qualified url to make it work in cypress.
So I have a workaround, but why does cypress handle it differently?

Why stub in cypress may not work for route called after page was loaded

I am using cypress to write tests and have a problem which doesn't appear in every test. In some cases it works and I don't know why. So...
The Problem:
I defined a route and alias for it in beforeEach:
beforeEach(function () {
cy.server()
cy.route('GET', '/favourites?funcName=columnPreset', []).as('columnPresetEmpty')
cy.visit('#/search')
})
Stub works fine if http request occured on page load.
But if I perform request responding to click event (modal dialog opens and executes http request) it just appear in commands not makred as stubbed and following cy.wait('#columnPresetEmpty') fails with request timeout.
it('does not work', function () {
cy.get('[data-test=button-gridSettings]').click()
cy.wait('#columnPresetEmpty')
})
At the same time in other tests I have almost similar functionality where request is performed just by clicking on a button, without opening new modal window. It's the only difference.
What am I doing wrong?
The issue might be cypress can not yet fully handle fetch calls. You can disable it the following way but make sure you have fetch polyfill. This will then issue XHR requests which cypress can observe.
cy.visit('#/search', {
onBeforeLoad: (win) => {
win.fetch = null
}
})
More to read here:
https://github.com/cypress-io/cypress/issues/95#issuecomment-281273126
I found the reason causing such behavior. Problem was not in a modal window itself, but code performing second request was called in promise's callback of another request. Something like:
fetch('/initData')
.then(loadView)
And loadView function executed second fetch.
So when I removed loadView from promise's callback both requests become visible for cypress.
For info, I tried it out on my search modal (in a Vue app) and it works ok.
What I did:
created a dummy file named test-get-in-modal.txt in the app's static folder
added an http.get('test-get-in-modal.txt') inside the modal code, so it only runs after the modal is open
in the spec, did a cy.server(), cy.route('GET', 'test-get-in-modal.txt', []).as('testGetInModal') in a before()
in the it() added cy.wait('#testGetInModal') which succeeded
changed to cy.route('GET', 'not-the-file-you-are-looking-for.txt'..., which failed as expected
The only difference I can see is that I cy.visit() the page prior to cy.server(), which is not the documented pattern but seems to be ok in this scenario.

Check if Resource Exists in Polymer Framework

I am trying to pull in product images in a dom-repeat template, but am getting 404 errors for missing resources showing up in the console.log. I would like to clean up the log with more legitimate errors.
<template is="dom-repeat" items="" index-as="index">
<lazy-image class="center"
placeholder="/images/placeholder.png"
src="https://www.images.com/[[formatImg(item.id)]].png"
style="width: 24pt; height: 24pt;">
</lazy-image>
</template>
...
formatImg(id) {
if(typeof id != 'null') return id.replace(' ', '%20');
}
I've seen some documentation on on-error events, but am not seeing a straight forward path to implement them into the Polymer framework.
Is there a way to handle these GET requests so they don't get logged?
Short answer:
Sadly, no.
It's not a "can't do it in Polymer" thing. At the time of writing, handling 404s to prevent a console error is not possible at all from the developer's point of view.
Longer answer:
AFAICT there is no way for a web developer to prevent a 404 from being logged by a browser as an error. If a browser is asked "get this thing please" or even "hey can you check if this is a thing?" and the answer is "that's not a thing", it is up to the browser what it does with that information. Right now, what it does (welp, Chrome anyway - I haven't researched what the others do) is "log an error to the console". Always. No matter what.
You can (as the end user) turn that behavior off in your browser. But you can NOT (as a developer) "catch" the error and handle it to keep the browser happy. Even if you DO handle the error and give the browser something that exists instead of the 404-causing resource, it will STILL be logged in the console as an error:
<!-- STILL CAUSES A 404 ERROR TO BE LOGGED TO THE CONSOLE -->
<img id="myimg" src="imagethatdoesntexist.gif" onerror="this.onerror=null;this.src='imagethatexists.gif';">
Source: Trial and error && this thread https://bugs.chromium.org/p/chromium/issues/detail?id=124534#c17

Resources