How to set headers on every request in Cypress using cy.intercept - cypress

I am trying to add a request header to every api request generated in Cypress. I have a version that works using cy.server but this is being depricated, so I am trying to replace it with cy.intercept. I don't see any errors when I run this code, but I don't see the header added to my requests either:
beforeEach(() => {
cy.intercept('*',(req) => {
console.log('MATCHED INTERCEPT')
req.headers['my-test'] = 'TEST'
})
})
I can see the log text 'MATCHED INTERCEPT' in the console, so I know that the intercept is matching something....
Can anyone tell me what is wrong with this code?

I think you will not be able to see the new header after intercepting, as per their documentation :
Hope this was useful

Related

How can I capture all 307 redirects with Cypress?

I am trying to test that a backend redirect url includes a certain parameter in the URL that it sends to google auth login. I can see the URL I want to test in the cypress logs when using headed mode, however I can't seem to be able to get access to that URL to confirm it includes the required text because that url ends up redirecting to a different final URL which is the one that my line ends up testing (see the failed line in the screenshot).
Does anyone know how to get access to that middle URL in the redirect chain?
I tried using
cy.on('url:changed', (url) => console.log(url))
but it similarly skips to the last URL
This had what I was looking for:
cy.request('/request/with/multiple/redirects')
.then((response) => {
response.redirects // redirect was in this array
})

Send header in subsequent URL visits through cypress

I am using Cypress for website integration testing and I am overwriting visit method such that it includes specific attribute in header but this doc says that headers will only be sent for the initial cy.visit() request, not for any subsequent requests.
Is there any workaround for this?
I know this question is asked long time ago but it might help others. I found a workaround to add headers for all requests:
cy.server({
onAnyRequest: function (route, proxy) {
proxy.xhr.setRequestHeader('CUSTOM-HEADER', 'Header value');
}
});

Network requests not showing up in cypress command log

We are trying to write a cypress test that checks one of the xhr requests made from the page. However the requests that we are making are not showing up in the command log. They do however show up in the bash console after running cypress open.
Command log:
Bash console:
We have tried running our simple test against other domains such as cypress.io, and google.com. Requests show up just fine.
We have verified that the requests made are not fetch requests.
We have disabled chomeWebSecurity (not sure if relevant).
Here is the example we are using:
describe('example', () => {
it('visits a page', () => {
cy.server();
cy.route('POST', '**');
cy.visit('https://www.academia.edu/12297791/Open_Access_Meets_Discoverability_Citations_to_Articles_Posted_to_Academia.edu');
});
});
Here is our cypress.json file:
{
"chromeWebSecurity": false
}
We are running cypress version 3.4.1
I would expect the command log to have these post requests show up, like this documentation describes: https://docs.cypress.io/guides/guides/network-requests.html#Requests
Any help is greatly appreciated, as we're unsure how else to debug this.
1.) I would suggest to use a more up-to-date version of Cypress with the cy.intercept().
2.) A typical problem can be the timing - add a cy.wait(X) before it, or add a timeout to replace the default timeout.
3.) Make sure the path of the route/intercept, especially when it differs from the cy.visit() 's url.
4.) Additional hint, use aliases.

Vuejs Axios POST request gets HTTP422 error from Laravel backend

Hi I am using Vuejs in the frontend and Laravel in the backend. The role of Laravel is handling the API only. The frontend and backend are separated, i.e. I am not using Vuejs in Laravel's resource/js folder.
Now I am sending Axios POST request from Vuejs to Laravel. All the form input values are prevalidated using HTML5 required attribute. And when I console.log the request data, it shows all the fields filled.
In Vue file:
const data = {
name: this.name,
gender: this.gender,
mobile_no: this.mobile_no,
image: this.userImage
};
console.log("Request data . . . .", data);
const response = await this.axios
.post(`${this.AppURL}/admin/user/create`, data, {
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(() => {
console.log("Success. . . . ")
alert("Successfully Driver Added");
})
.catch(error => console.log(error));
And in Laravel, the request is passed through some validation. It's a simple validation to check if all the fields are filled.
I am also using JWTAuth package for the authentication, and the token is generated by it.
It's too much code to write them all the way down here. But I am sure you can understand what I mean.
What I am getting as a response is this
POST http://localhost:8000/api/admin/user/create 422 (Unprocessable Entity)
The actual result I am expected to get is either success or some errors that is according to some if conditions in validation or token check.
I tried to figure out where this error might come from. What I think at the moment is this could be due to the absence of csrf_token in the POST request. As I'm sending the request outside Laravel, csrf_token is missing in the form. I am not 100% sure though about this.
So my question is:
How can I include csrf_token in Axios POST request, when I send it from outside Laravel.
If this 422 error is not related with csrf_token, what could be causing this? Any previos experiences like min? and any solutions for this?
Thanks in advance for your help.
Please, modified catch block as #Jack suggested:
.catch(error => {
console.log("ERRRR:: ",error.response.data);
});
Now you can get errors and handle errors in the catch block.
.catch(function (error) {
console.log(error.response.data.errors);
});
please use this code I hope it work's.
I was also facing the same issue, i think it is due to some Headers missing in your Api request from vue.js. here some tips which may helps you to solve this issues.
Make sure that you are protecting your Api Routes or not(by sanctum or something else). If you are protecting , then make make sure that you are sending authentications token in headers.
Second make sure that your request(axios or jwt) should contained valid data, if your are sending images or files etc make sure how can we send them.
First, get request and check in laravel by dd($erquest->all()); if you are geeting data then validate, it is possible that laravel request doesnt contained your sending data..
These errors may be caused due to follow reasons, ensure the following steps are followed.
To connect the local host with the local virtual machine(host).
Here, I'am connecting http://localhost:3001/ to the http://abc.test
Steps to be followed:
We have to allow CORS, placing Access-Control-Allow-Origin:* in header of request may not work. Install a google extension which enables a CORS request.
Make sure the credentials you provide in the request are valid.
Make sure the vagrant has been provisioned. Try vagrant up --provision
this make the localhost connect to db of the homestead.
Just click on the preview tab within network section in the dev tool, you are going to see the actual error message.

Signin request failing due to invalid csrf

I am testing a signin page for keystonejs (http://demo.keystonejs.com/) and cannot get the request to succeed with cypress. A signin request without cypress has the following request headers:
while a request with a cypress test has the following request headers:
The only difference I can see is that the cookie is not set in the cypress test request. And because of that the request gets a 403. I am actually using a local version of that server in which I have the email/password configured as the one in the images. The demo site uses a different set provided in that page.
The test is simply:
describe('The Keystone Admin UI Signin Page', function () {
before(function() {
cy.visit('http://localhost:3000/keystone/signin')
})
it('should signin successfully with valid email/password', function () {
cy.get('#signin-view input[name=email]').clear().type('user#test.e2e');
cy.get('#signin-view input[name=password]').clear().type('test');
cy.get('#signin-view button[type=submit]').click();
cy.get('#react-root').should('be.visible');
})
})
Anyway to get around this?
I know this is an older question but I'll post this in case it helps anyone.
The key to fixing this issue for me was that Cypress clears all cookies before each test (https://docs.cypress.io/api/commands/clearcookies.html#).
So in the example above (and in my experience):
The first test (loading the page) is run and passes fine - at this point the browser has set the csrftoken cookie
The second test (submitting the form) runs but before this happens Cypress has deleted the csrftoken cookie - hence the error
To fix this I had to whitelist the csrftoken cookie in Cypress config which means that it will be exempt from this clearing process:
Cypress.Cookies.defaults({
whitelist: "csrftoken"
})
You can do this inline in your test file but the docs recommend using a support file:
A great place to put this configuration is in your cypress/support/index.js file, since it is loaded before any test files are evaluated.
Hope this helps, Stephen.
Following on from FlatSteve's answer, using with Laravel and updated prop names use;
Cypress.Cookies.defaults({
preserve: ["XSRF-TOKEN", "your_laravel_session_name", "remember_token"]
});

Resources