POST request not working in Cypress plugin - fetch-api

I want to do a POST request after Cypress has been run:
module.exports = (on, config) => {
on('after:run', (results) => {
console.log('Failed tests: ', results.totalFailed)
fetch('https://status.**.**/api/webhook/cypress-e2e-testing', {
method: 'POST',
headers: { Authorization: 'Bearer Hk0WkGZMjckIxpIgSlpSVVe2g2DYibYCKMyV5SBdRYng8Ash****' }
})
.then(console.log('fetch'))
})
}
In the Cypress log I do see the fetch but the POST doesn't seem to work.
The URL for the post is a API end point that, when a POST request is received, set's a 24 hour countdown (it expects a POST request each 24 hours). When I use Postman the countdown is reset to 24 hours again:
But using the fetch in the script nothing seems to happen.

Related

CORS error: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response

I'm trying to fetch an image resource that's part of a conversation message.
I've tried both FETCH as well as using AXIOS but I'm getting the same error message.
Here's an example of my FETCH request
const token = `${accountSid}:${authToken}`;
const encodedToken = Buffer.from(token).toString('base64');
let response = await fetch('https://mcs.us1.twilio.com/v1/Services/<SERVICE_SID>/Media/<MEDIA_SID>',
{
method:'GET',
headers: {
'Authorization': `Basic ${encodedToken}`,
}
});
let data = await response.json();
console.log(data);
And here's what Axios looked like
let config = {
method: 'get',
crossdomain: true,
url: 'https://mcs.us1.twilio.com/v1/Services/<SERVICE_SID>/Media/<MEDIA_SID>',
headers: {
'Authorization': `Basic ${encodedToken}`,
},
};
try {
const media = await axios(config);
console.dir(media);
} catch(err) {
console.error(err);
}
Both ways are NOT working.
After looking into it more, I found out that Chrome makes a pre-flight request and as part of that requests the allowed headers from the server.
The response that came back was this
as you can see, in the "Response Headers" I don't see the Access-Control-Allow-Headers which should have been set to Authorization
What am I missing here?
I have made sure that my id/password as well as the URL i'm using are fine. In fact, I've ran this request through POSTMAN on my local machine and that returned the results just fine. The issue is ONLY happening when I do it in my code and run it in the browser.
I figured it out.
I don't have to make an http call to get the URL. It can be retrieved by simply
media.getContentTemporaryUrl();

Can't login by Goggle accounts connect or by Google auth API in Cypress 10x

Current behavior
I've tried to connect to Google account when my tested application redirects to Google accounts connect for let the end-user send emails by the application but I'm not able to do it not by Google Auth API according to your guidelines:
https://docs.cypress.io/guides/end-to-end-testing/google-authentication#Custom-Command-for-Google-Authentication
and not by cy.origin() from the UI.
In the first attempt by the API it's ignore of these authentication and popup the dialog to connect by google account as usually even all the credentials and token are valid and return 200 ok.
In the second attempt by cy.origin() it's keep to load the page after the redirect and always reach to timeout and yell about to increase the timeout even the page seems like it was fully loaded after a few seconds.
I've tried to increase the timeout to 90 seconds and use wait() before and after the redirect and look for some hidden iframes and tried every versa of google domain but nothing help.
it always return errors over there.
all the examples are below.
This is the error when trying to use cy.origin()::
Timed out after waiting 30000ms for your remote page to load on origin(s):
- https://google.com
A cross-origin request for https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fmail.google.com&include_granted_scopes=true&state=%7B%22redirectUri%22%3A%22https%3A%2F%2Fmyappurl.com%2Fapp%2Fpipeline%2F9some-token-here-b96b599154ac%3Ftab%3Doverview%22%2C%22clientToken%22%3A%mytokenishere-1234567890%22%7D&prompt=consent&response_type=code&client_id=1234567890-aehhht36f7a01d38bmsvvpjrh915i86v.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fmyredreictedappurl.com%2FusersManagerSrvGoogleLogin was detected.
A command that triggers cross-origin navigation must be immediately followed by a cy.origin() command:
cy.origin('https://google.com', () => {
<commands targeting https://accounts.google.com go here>
})
If the cross-origin request was an intermediary state, you can try increasing the pageLoadTimeout value in Users/myname/repos/myreponame/cypress.config.ts to wait longer.
Browsers will not fire the load event until all stylesheets and scripts are done downloading.
When this load event occurs, Cypress will continue running commands.[Learn more](https://on.cypress.io/origin)
Desired behavior
No response
Test code to reproduce
commands.ts
Cypress.Commands.add('loginByGoogleApi', () => {
cy.log('Logging in to Google')
cy.request({
method: 'POST',
url: 'https://www.googleapis.com/oauth2/v4/token',
body: {
grant_type: 'refresh_token',
client_id: Cypress.env('googleClientId'),
client_secret: Cypress.env('googleClientSecret'),
refresh_token: Cypress.env('googleRefreshToken'),
},
}).then(({ body }) => {
const { access_token, id_token } = body
cy.request({
method: 'GET',
url: 'https://www.googleapis.com/oauth2/v3/userinfo',
headers: { Authorization: `Bearer ${access_token}` },
}).then(({ body }) => {
cy.log(body)
const userItem = {
token: id_token,
user: {
googleId: body.sub,
email: body.email,
givenName: body.given_name,
familyName: body.family_name,
imageUrl: body.picture,
},
}
window.localStorage.setItem('googleCypress', JSON.stringify(userItem))
cy.visit('/')
})
})
})
test-file.cy.ts
it.only('Send email to a user - is shown in the activity', () => {
cy.loginByGoogleApi();
cy.get(loc.sideNavBar.buyersPipeline).should('be.visible').click();
cy.get(loc.pipelineBuyer.nameColumn)
.eq(4)
.should('be.visible')
.click({ force: true });
cy.get(loc.buyerDetails.basicCard).should('be.visible');
cy.get(loc.buyerDetails.timelineSendEmailIcon)
.should('be.visible')
.click();
cy.get('div[role="dialog"]').find('button.MuiButton-root').should('be.visible').click();
})
})
By cy.origin() by the UI:
test-file.cy.ts
it.only('Send email to a user - is shown in the activity', () => {
// cy.loginByGoogleApi();
cy.get(loc.sideNavBar.buyersPipeline).should('be.visible').click();
cy.get(loc.pipelineBuyer.nameColumn)
.eq(4)
.should('be.visible')
.click({ force: true });
cy.get(loc.buyerDetails.basicCard).should('be.visible');
cy.get(loc.buyerDetails.timelineSendEmailIcon)
.should('be.visible')
.click();
cy.get('div[role="dialog"]').find('button.MuiButton-root').should('be.visible').click();
cy.wait(5000);
cy.origin('https://accounts.google.com', () => {
cy.wait(5000);
expect(window.origin).contains('google.com')
cy.get('input[type="email"]', {timeout: 60000}).should('be.visible', {timeout: 60000}).type('111');
})
});
````
### Cypress Version
10.7.0
### Node version
v14.19.1
### Operating System
macOS Montery 12.3.1

How can I reach the 'Retry-After' response header using axios?

I'm building a simple Vue2 app with Auth section, which makes requests to REST API service.
So, I have my axios instance:
const instance = axios.create({
baseURL: BASE_URL,
timeout: DEFAULT_TIMEOUT,
withCredentials: true,
headers: {
accept: 'application/json',
},
});
To make authorization requests I use a separate module:
const auth = (api) => ({
submitPhoneNumber({ userPhone }) {
return api.get(`auth/${userPhone}`);
},
});
And set it all up together like this:
export default {
auth: auth(instance),
};
Then I add my api to Vue as a plugin:
export default {
install(Vue) {
const vueInstance = Vue;
vueInstance.prototype.$api = api;
},
};
In the component I access my api-plugin and make a request, extracting status and headers from it:
const { status, headers } = await this.$api.auth.submitPhoneNumber({
userPhone: this.userPhone,
});
When I look through the response in chrome devtools, I clearly see a "retry-after" header with number of seconds, after which I can make another request.
Upon receiving the response, I would like to save this number of seconds to some variable and then render a warning message like "Please wait { seconds } to make another submit".
The problem is that in my code I have no such header in the response (while I can see it in devtools, a I said):
see the screenshot
So, when logging the headers from my response, there are just these:
{content-length: '19', content-type: 'application/json; charset=utf-8'}
What is the problem with that?
Try var retrysec = error.response.data.retry_after that worked for me

Transferring bearer token from API request to other tests using Cypress

I am running tests on a web application to test WYSIWYG functionality and XSS vulnerabilities. I use the following command before
beforeEACH(() => {
cy.vaderAuth()
});
Cypress.Commands.add('vaderAuth', () => {
let config = Cypress.config();
cy.request({
method: 'POST',
url: Cypress.config('tokenUrl') + '/api/v1?actions=api/v1/login',
body: {
username: config.horizon.username,
password: config.horizon.password,
}
}).then(response => {
window.localStorage.setItem('JWT', response.body['api/v1/login'].token)
})
})
The above command successfully gets the Bearer Token but then the following test throws a 401 Unauthorised error.
it('Sending a regular API request to Welcome Messages', function() {
cy.request({
method : 'POST',
url : '/api/v1/organisations/welcome-message?actions=api/v1/organisations/welcome-message/set-welcome-messages',
body : {"welcome_messages":[{"message":"<p>Test investor welcome message!</p>","type":"User"},{"message":"<p>Internal User welcome message Cypress Test. </p>","type":"Internal User"},{"message":"<p>Test entrepreneur welcome message!</p>","type":"Entrepreneur"}]},
headers : {"Authorization": "Bearer " + window.localStorage.JWT}
})
})
beforeEach working, API request 401
401 cypress error
I have checked the failure and it is sending the Bearer Token as a header, and the request headers match the headers the same request sends if I enter the Bearer Token manually as follows.
it('Sending a regular API request to Welcome Messages', function() {
cy.request({
method : 'POST',
url : '/api/v1/organisations/welcome-message?actions=api/v1/organisations/welcome-message/set-welcome-messages',
body : {"welcome_messages":[{"message":"<p>Test investor welcome message!</p>","type":"User"},{"message":"<p>Internal User welcome message Cypress Test. </p>","type":"Internal User"},{"message":"<p>Test entrepreneur welcome message!</p>","type":"Entrepreneur"}]},
//headers : {"Authorization": "Bearer (insertbearertokenhere)}
})
})
When entering the Bearer Token manually the following tests all run smoothly with no error, but if I have to go in and change the Bearer Token every time I run these tests, it kind of defeats the point of automating it as by the time I've logged into my web app and got the token, I may as well test the application manually.
Any help on this would be greatly appreciated as I have been working on it with no luck for around a week now.

Promise response works with GET, but not with POST in XHR

I am trying to call a URL through XHR.post on the DOJO 1.8. I need catch the STATUS property and getHeader() from promise response, but the problem is, when I call my URL with POST I don't have any promise, and when I call with GET I have all properties that I need, but I only can send the request as POST.
The most strange is that I have another code in AngularJS which works well, this code does the same thing. I am testing DOJO and AngularJS.
I need catch the STATUS information to check if it is 201(created), if true I need catch getHeader('location') and call the URL that I picked up from getHeader('location').
Look at my method in Dojo 1.8:
checkCreation: function(typeFile, id){
var promise = xhr('/rest/list/one', {
handleAs: 'json',
method: 'post',
accepts: 'application/json',
headers: {
Accept: 'application/json',
id: id,
type: typeFile
}
});
promise.response.then(function(response) {
console.log("status", response.status);
console.log("options", response.options);
console.log("url", response.url);
console.log("timestamp", response.options.timestamp);
console.log(response);
});
},
I discovered the problem, I commented the lines followings and now works fine.
//handleAs: 'json',
//accepts: 'application/json',
The handleAs you need to use only when you have a JSON response. About "accepts" I haven't found what difference between "accept" and "Accept"(inside headers) yet.
Now I can take my informations:
console.log('location: ', response.getHeader('location'));
console.log("status: ", response.status);