Not able to mock GET request in cypress - reactjs

x.spec.js
before(() => {
cy.restoreLocalStorage();
cy.server()
cy.route({
method: 'GET',
url: '/dashboard/v1/public/api/allMachineStatus',
headers: {
"access-control-allow-credentials": true,
"authorization": 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXiOjE1OTI0MDU5NjMsImV4cCI6MTU5NDk5Nzk2MywiaWQiOiIxMDAwIiwiaXNfYWRtaW4iOnRydWV9.JaIUHy85pIZ_rulJCZXutqZXeC_4_wlVFa4z3I-8kO0'
},
response: 'fixture:allMachinesStatus'
})
cy.visit('/')
cy.get('[data-testid="side-bar')
.contains('Live Status')
.click()
});
beforeEach(() => {
cy.wait(100)
})
context("it should check headings",()=>{
it("should check some heading",()=>{
cy.get('[data-testid="refill-status-heading-live-status"]')
})
})
Above is the test code and
{
"error": false,
"data": [
{
"machine_id": "...",
"total_units": 550,
"total_price": "50"
}
]
}
this is in allMachinesStatus.json
When i load page i make **GET** request but i can not see that request in cypress logs
So the code here x.spec.js is also not mocking it. I am able to mock POST request but this get request is on page load and i dont know why its failing.
I have post request (timings in response headers are)
**..getPaymentMethods** - date: Sat, 20 Jun 2020 16:04:14 GMT // post request
**...allMachineStatus** - date: Sat, 20 Jun 2020 16:04:13 GMT // get request that is not showing up on cy browser

Related

Cancel Subscription Paypal API + Axios + React

I'm stuck with a Paypal Smart buttons error that says 401 (Unauthorized)
The business solution is paid for and everything that should be authorized is.
This is the function I created. Anything in-between [ ] are placement holders of private info:
cancelSubscription = () => {
axios({
url: `https://api.paypal.com/v1/billing/subscriptions/[USER_SUBSCRIPTION_ID]/cancel`,
method: 'post',
headers: { "Content-Type": "application/json", "Authorization": "Bearer [FACILITATOR_ACCESS_TOKEN]" },
data: { "reason": "test -- Not satisfied with the service" }
})
.then(res => {
console.log(`Axios Call completed: ${res}`)
});
}
I don't see a problem with your code, so the clientid, access token, and full response body+response headers (including a PayPal-Debug-Id) will all have to be looked at to troubleshoot a 401. Submit this information to PayPal's support if you aren't going to post it here.

How to access headers in react.js frontend built by rails backend?

I have a get endpoint in billings_controller.rb like:
def index
plans = PricingPlan.all
response.header['publishable-key'] = Rails.configuration.stripe[:publishable_key]
render json: { status: true, message: 'List of Plans.', data: plans.to_a }
end
Now, I would like to access that HTTP header in react.js front-end app, the way I'm doing is like:
componentDidMount() {
zenApi.get(SERVER)
.then(response => {
this.setState({ pricing_plans: response.data, pub_key: response.headers['publishable-key'] });
});
}
But the response.headers is undefined. console.log(response) gives as:
{status: true, message: "List of Plans.", data: Array(6)}
but, when I look HTTP response headers in network tab in chrome developers tools, it looks like:
HTTP/1.1 304 Not Modified
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS, DELETE, PUT, PATCH
Access-Control-Expose-Headers: access-token, expiry, token-type, uid, client
Access-Control-Max-Age: 1728000
publishable-key: pk_test_fYfWQWtbSsGbb1*****50VrT
ETag: W/"15cb9de83c1d4eb95f83936d5413c695"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: b5288bbe-6783-4516-b628-110c1a29ea05
X-Runtime: 0.593409
Vary: Origin
I'm missing something or have't understood the concept I think. How can I access the "publishable-key: pk_test_fYfWQWtbSsGbb1*****50VrT" present in HTTP response header in react.js front-end.
Thank you all.
You can access $http headers like this:response.headers();
componentDidMount() {
zenApi.get(SERVER)
.then(response => {
var headers = response.headers();
var publishable_key = headers['publishable-key']
this.setState({ pricing_plans: response.data, pub_key: response.headers['publishable-key'] });
});
}

Handling REST errors in AngularJS

I have written a REST service that deals with errors like this:
return Response.status(vr.responseStatus).entity("Oh No")
.type(MediaType.APPLICATION_JSON).build();
On the client side, I have called this:
var request = $http({
method: "put",
url: serviceProvidersURL,
params: {
//action: "add"
},
data: item
});
return( request
.then( handleSuccess,
function(response){
alert("Here1: " + response);
alert("Here2") + JSON.stringify(response);
})
);
Both the alerts are failing to deal with the response. In the first alert, I get "Here1: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data" and the second alert, I just get "Here2"
If I look at the response in firebug, the "Oh No!" is in the response section and these are the headers:
HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: application/json
Transfer-Encoding: chunked
Date: Wed, 08 Jun 2016 06:49:57 GMT
Connection: close
The Oh No! is definitely in the response body - I have no idea how to get to it through the client side.
Thanks

How to setup e2e protractor backend request mocking/stubbing

I try to setup my independent protractor project to mock some of my backend requests. Therefore, I included angular-mocks.js and attached another module within the onPrepare() function of my protractor.conf.js:
browser.addMockModule('httpBackend', function() {
angular.module('httpBackend', ['myApp', 'ngMockE2E']).run(function($httpBackend) {
$httpBackend.whenPOST(/^requests\/*/).respond(function(method, url, data) {
var obj = {"msg": "Response!"};
return [200, JSON.stringify(obj), {}];
});
})
})
This lets me intercept any request but I am not getting what I want to return in respond(). It seems I am just getting a 200 OK.
What am I doing wrong?
Just to let you know how I solved it:
The docs say the following:
The respond method takes a set of static data to be returned or a function that can return an array containing response status (number), response data (string), response headers (Object), and the text for the status (string).
In my case, the headers Object somehow does not seem to be optional and I ended with setting it on my own before returning the array:
browser.addMockModule('httpBackend', function() {
angular.module('httpBackend', ['myApp', 'ngMockE2E']).run(function($httpBackend) {
$httpBackend.whenPOST(/^requests\/*/).respond(function(method, url, data) {
var obj = {"msg": "Response!"},
resHeader = {
"Cache-Control": "no-cache, no-store, max-age=0",
"Date": "Tue, 24 Nov 2015 17:08:57 GMT",
"Pragma": "no-cache",
"Transfer-Encoding": "chunked",
"Content-Type": "application/json; charset=UTF-8",
"Expires": "Thu, 01 Jan 1970 00:00:00 GMT",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "origin,x-requested-with,access-control-request-headers,content-type,access-control-request-method,accept",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS, DELETE",
"Access-Control-Credentials": "true",
"Content-Language": "de-DE",
"Access-Control-Max-Age": "3600"
};
return [200, JSON.stringify(obj), resHeader];
});
})
})
Anybody has a clue why this is necessary or which of its attributes is obsolete?

AngularJS $http date header

I'm trying to retrieve the $http date header from an AngularJS $http.get request so I can get the server time.
app.controller('MainCtrl', function($http,$scope) {
$scope.name = 'World';
$http({method: 'GET', url: 'http://graph.facebook.com/facebook'}).then(function(response){
console.log(response);
})
});
I can't seem to retrieve the Date header although when I inspected on chrome tools the date header was there.
try this:
$http({method: 'GET', url: 'http://graph.facebook.com/facebook'}).then(function(response){
var data = response.data,
status = response.status,
headers = response.headers(),
config = response.config;
})
headers will contain:
headers: {
"date": "Mon, 02 Mar 2015 23:02:51 GMT",
"content-encoding": "gzip",
"server": "Apache",
"vary": "Accept-Encoding",
"content-type": "text/html",
"connection": "Keep-Alive",
"keep-alive": "timeout=10, max=500",
"content-length": "39"
}
to access date:
headers.date
Since it's a CORS request to facebook api: The response header will contain only
Content-Type
Last-modified
Content-Language
Cache-Control
Expires
Pragma
The issue is because of missing Access-Control-Allow-Headers from request Header. To fix this we need to add Access-Control-Allow-Headers: * to request header in your run method

Resources