How to avoid timeout error for cy.request()? - cypress

I am using cy.request() method to send API requests and read the response in my cypress tests. But sometimes the tests fail with the following error:
CypressError: cy.request() timed out waiting 30000ms for a response from your server.
I have increased the timeout value by passing in timeout: 50000 option in the request body, but still, it is failing sometimes especially when the response is huge. Is there any other way to avoid the request timeout error?
Below is my code:
cy.request({
method: "POST",
url:"http://localhost:3001/codes/search?searchText=" +searchText.replace(" ", "%20") +"&page[size]=100",
body: {
data: {
type: "ern:code-search-request",
attributes: {
CodeCategory: filterOption
}
}
},
timeout: 50000
}).then((response: any) => {return response;})

You can use responsetimeout in cypress.json file. Cypress docs

Related

Receiving 403 Forbidden error when running Cypress test, but receiving no error when manually navigating to the app

Below is a step in my Cypress test:
Given('I visit the webiste', () => {
cy.visit('https://dealerportal-test.santanderconsumerusa.com/dealer/login/')
})
Actual Cypress Behaviour:
I get a 403 error below:
cy.visit() failed trying to load:
https://dealerportal-test.santanderconsumerusa.com/dealer/login/
The response we received from your web server was:
403: Forbidden
This was considered a failure because the status code was not 2xx.
If you do not want status codes to cause failures pass the option:
failOnStatusCode: false
Actual Manual Behaviour:
I'm able to manually navigate to the website without a problem, & here are the network requests being made:
Is there a better way to handle this issue rather than just setting failOnStatusCode: false?
I'm not sure why the manual behaviour is different to the automated behaviour
In your cypress.json config file write this:
{
"baseUrl": "https://dealerportal-test.santanderconsumerusa.com",
"chromeWebSecurity": false
}
Then in yor test try this:
cy.visit('/', {
headers: {
'accept': 'application/json, text/plain, */*',
'user-agent': 'axios/0.27.2'
}
});

500 Server Error in Cypress tests to one of the AJAX request

I'm facing an issue while working with Cypress test on a Drupal 8 based website, I'm getting a 500 server error when one of the button is clicked which invokes AJAX command, it works perfectly fine when I'm browsing the same page locally but Cypress is immediately throwing a 500 Server Error.
As described here by #NoriSte, I've tried the following code using https://www.npmjs.com/package/cypress-wait-until cy.waitUntil & updated the selectors, etc., the code is attempting/clicking the button multiple times but in all the request the AJAX is getting 500.
// This will be set to true when the XHR request starts.
let requestStarted = false
cy.server()
cy.route({
method: 'POST',
url: '/the-ajax-url?*',
onRequest: () => (requestStarted = true)
}).as('sendCommand');
cy.get('.the-button-selector').as('button')
cy.waitUntil(() => cy.get('#button')
.should('be.visible')
.click({force: true})
.then(() => requestStarted === true), {
timeout: 20000,
interval: 1000,
errorMsg: 'POST not sent `enter code here` within time limit'
})
cy.wait('#sendCommand')
What I'm trying to achieve is to allow this AJAX request some time, so instead of quickly throwing 500 error, it loads up & works as expected.
Note: This AJAX request response in actual is approx ~1.5 MB, not sure if somehow this could be helpful.
Two things seem to be indicated by the log
the route is not capturing the url (because the error message says so)
suggest testing with Cypress.minimatch, perhaps simplify to url: '/the-ajax-url'
the route should specify status: 201, otherwise once the url matches it seems likely to capture the 500 status and set requestStarted true, which is not what you want.
cy.waitUntil() is not waiting because requestStarted === true cannot be true, since the route didn't capture.
check out this as an alternative way to retry cypress xhr request retry ontimeout. cy.waitUntil() uses recursion under the hood, but it's not entirely clear how to the until part works. Going to a simpler recursive function will give you more clarity.

How do I set the status code of response when stubbing server using Cypress

I am trying to stub a server response so that when the server is down I can see a given error webpage. My challenge now is that the server is getting stubbed with the code below, but I would like to stub not just the response body but the status code as well.
const apiUrl = "https://webtmanial.dadaere.com/judadalerer"
cy.server()
cy.route(
'POST',
apiUrl,
500
).as('dadaResponse');
The response is stubbed using the above, but status code still returns as 200 as shown below
Status: 200 (OK)
cypress_runner.js:171102 Duration: 673
cypress_runner.js:171102 Stubbed: Yes
cypress_runner.js:171102 Request: {headers: {…}, body: {…}}
cypress_runner.js:171102 Response: {headers: {…}, body: 500}
The Cypress doc have examples for stubbing the response, but there's no clear example of stubbing the status code.
Please is there a way I can set the status code for the stubbed server, so that it returns 500. Thank you
You can pass the status in options object as below:
cy.route({
method: 'POST',
url: apiUrl,
status: 500,
response: '{"error":"Some error"}', // json object stringified!
});

API Gateway, blocked by CORS policy: No 'Access-Control-Allow-Origin' header

I know this question might be duplicated, but none of the existing question point to anything I'm not doing...
I've deployed an API using the serverless framework, but I'm having trouble with CORS.
I'm doing a get request using axios:
axios.get('https://test.execute-api.us-west-1.amazonaws.com/dev/test?from=2012-01-09T21:40:00Z')
.then(response => {
this.data = response.data;
})
.catch(error => console.log(error))
And I'm getting the following error:
Access to XMLHttpRequest at 'https://test.execute-api.us-west-1.amazonaws.com/dev/test?from=2012-01-09T21:40:00Z' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
What I've already done:
Made sure there's an OPTIONS method in API Gateway with a method response that looks like this:
Made sure I deployed those changes.
Also, the response of my Lambda function is returning the following headers:
return events.APIGatewayProxyResponse{
StatusCode: http.StatusOK,
Headers: map[string]string{
"Access-Control-Allow-Origin": "http://localhost:8080",
"Access-Control-Allow-Credentials": "true",
},
Body: string(jsonEvents),
}, nil
I also tried setting Access-Control-Allow-Origin to '*'
My serverless.yml file has cors: true on each of the function events:
functions:
deploymentFrequency:
handler: bin/update/deployment-frequency
events:
- http:
path: deployment-frequency
method: post
cors: true
fetchDeploymentFrequency:
handler: bin/fetch/deployment-frequency
events:
- http:
path: deployment-frequency
method: get
cors: true
What am I missing? Nothing seems to work. The request works fine from Postman and it looks to be including the headers, so this seems to be an issue with the OPTIONS method.
My configuration is:
(event, context, callback) => {
callback(null, {
statusCode: (code || 200),
body: JSON.stringify(resp),
headers: { 'Access-Control-Allow-Origin': '*'},
});
}
and it works fine for me. I use to have the same issue as you before, but as long as you define your function with CORS: true and your response contains the header, you should be fine.
Note: Im didnt understand the sintax "map[string]string" and credentials should not be necessary at this case.
It turns out I was ignoring the status code from the response :(
I realized I was actually getting two errors:
A 406 status code for a missing Content-Type header
The CORS error
The first error was caused because I wasn't passing the Content-Type header to the request (I had a check in my code I completely forget that expects that header).
The second error was caused because I didn't add the Access-Control-Allow-Origin header to the error response of my function.
Enable Lamba proxy integration
return events.APIGatewayProxyResponse{
StatusCode: http.StatusOK,
Headers: map[string]string{
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
},
Body: string(jsonEvents),
}, nil
In your terminal, go to the root project path and run:
npm i cors
And, after you need put this code in your index.js:
const cors = require("cors");
app.use(cors());

Send message with Malign via http request

I try to send a message via http request using Mailgun, the system give me back a 200 ok but the message never send.
here my code, (I run my code inside a parse httpReuest function) any idea?
Parse.Cloud.httpRequest({
url: 'https://api:MYAPIKEY#api.mailgun.net/v3/MYDOMAIN.net/message',
params: {
from: 'XX#XX.net',
to: 'XX.XX#gmail.com',
subject: 'Hello',
text: 'Testing some Mailgun awesomness!'
}
}).then(function(httpResponse) {
console.log('Request response ' + httpResponse.error);
}, function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
});
I found the answer... I make a mistake in the api call the right call is.
url: 'https://api:MYAPIKEY#api.mailgun.net/v3/MYDOMAIN.net/messages',
with messages not message
forgot and s and waste the entire day :-(

Resources