cypress intercept stub and retrieve response - cypress

Hello so am relatively new to using intercept on cypress.
Clicking a button sends a request. Intercepting and not stubbing (//1) lets me retrieve the date value in the response seen in cy.log($resp.response), but I need to stub a response too (//2) this fails to return a date value in the cy.log($resp.response). The data value is generated as it is seen in the UI
How can I retrieve the response and still stub?
cy.intercept({method: 'POST', url: '**/myURL'}).as('successfulAction') //1
cy.intercept({method: 'POST', url: '**/myURL'},{stubbed data}).as('successfulAction') //2
cy.get('button').click()
cy.wait('#successfulAction').then(($resp) => {
cy.log($resp.response)
})

On the first intercept, add the middleware flag.
This allows the true request to be caught, but pass the request on to the 2nd intercept which applies stubbed data.
cy.intercept({
method: 'POST',
url: '**/myURL',
middleware: true
}).as('successfulAction')
cy.intercept({method: 'POST', url: '**/myURL'}, {stubbed data}) // no alias needed
cy.wait('#successfulAction')
.then(($resp) => {
cy.log($resp.response)
})

You can also use a single intercept
cy.intercept({
method: 'POST',
url: '**/myURL',
middleware: true
}).(req => {
req.continue(resp => {
cy.log($resp.response)
res = stubbedData
})
})
.as('successfulAction')

Thanks for the answers I definitely gave me an idea and the below works.
cy.intercept({
method: 'POST',
url: `**/${parentAlarmsAssetsData[0].AssetNumber}`,
middleware: true
},(req) => {
req.continue((res) => {
res.send({ //add stubbed data
statusCode: 200,
body: {
"status":true,
"responseMessage":null
}
})
})
}).as('successfulAction')
cy.get(manualCheckButton).click()
cy.wait('#successfulAction').then(($resp) => {
acknowledgedDateTime = $resp.response.headers.date //set global var
})

Related

Ajax Call return error like "The POST method is not supported for this route. Supported methods: OPTIONS " in Laravel

I am fetching some data from server using ajax on page loading. But these calls always returns error as The POST method is not supported for this route. Supported methods: OPTIONS. I have tried all the options I can but no use. Here is my code.
var today = new Date();
var monthYear = moment(today).format('MMM/YYYY');
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: baseUrl + 'statisticalboxes',
method: 'POST',
data: {
'project-month': monthYear
},
success: function(data) {
console.log(data);
},
error:function(e) {
console.log(e);
}
});
web.php
Route::post('statisticalboxes', ['as' => 'statisticalboxes','uses' => 'DashboardController#getStasticalBoxData']);
I have changed method into all other options, but no use.
When I look into the network tab, the requested url look like
Request URL: http://127.0.0.1:8000/nullstatisticalboxes, but the actual one is Request URL: http://127.0.0.1:8000/statisticalboxes
Your baseUrl variable return null value.
Where you define baseUrl?
Define baseUrl variable.
--- OR ---
Use url like this.
url: '/statisticalboxes',

how to store access token generated using cypress (request) so I can use this as Auth header to call other API's

How can I access the token parsed from JSON response
const getToken = () =>
cy.request({
method: 'GET',
url: '/generateToken'
});
.its('body')
.then((response) => {
JSON.parse(response)
token = token['accessToken'] //How can I access this token value to use in other It tests?
})
You could use this approach:
const getToken = () => {
cy.request({
method: 'GET',
url: '/generateToken'
}).its('body').then(function(response) {
json = JSON.parse(response)
this.token = json['accessToken']
})
}
// Afterwards...
it('should xxxxxxxx xxx xxx', () => {
console.log(this.token)
});
Please note that accessing aliases as properties with this.* will not work if you use arrow functions =>, this is the reason why I used function.

Can I log to file all the responses made during running cypress test?

When I'm running cypress e2e tests, application makes XHR requests. How can I log all this requests and responses? I don't want to stub these requests. I with to get an artifact with all requests and responses made during test. Gitlab is used as CI.
Main test code looks like this. All these are user defined commands, interacting with the application. Interacting with the application causes different requests to be made (e.g. I click a button, this causes the request).
it('Log response to a file',function(){
cy.request({
method: 'GET',
url: 'https://<site>/home/payments/currency/confirm/*',
headers: {
'Content-Type': 'application/json',
},
body: {},
}).then((response)=>{
const someResponse = response.body;
console.log("hhhh"+someResponse);
cy.writeFile('cypress/fixtures/testResponse.json', someResponse);
cy.login(login_name, pass)
cy.typeOTPpinpad(secret)
cy.makePayment('Currency', 'amount')
cy.typeToken(secret)
cy.logout()
})
})
Here is how I tried to use regular expression to catch request (id is unique and I need to use regular expressions).
https://<mysite>/home/payments/<currency>/confirm/* - asterisk is payment id.
You could grab the request and response and write to a location as below. I have write the request and response to fixture folder as below: Try the below and let me know
it('Log request to a file',function(){
cy.request({
method: 'GET',
url: 'url_here',
headers: {
'Content-Type': 'application/json',
},
body: {},
}).then((request)=>{
const someRequest = JSON.stringify(request);
console.log("hhhh"+someRequest);
cy.writeFile('cypress/fixtures/testRequest.json', someRequest);
})
})
// The below is for response:
it('Log response to a file',function(){
cy.request({
method: 'GET',
url: 'url_here',
headers: {
'Content-Type': 'application/json',
},
body: {},
}).then((response)=>{
const someResponse = response.body;
console.log("hhhh"+someResponse);
cy.writeFile('cypress/fixtures/testResponse.json', someResponse);
})
})
The testrunner has such information on board:
[

Cypress.io: How to read XML File and assign the contents to cy.request(body)

For one of my web service testing, I need to read an xml file and assign the contents of the same to cy.request body.
How can I achieve this?
I tried the below method and was not able to successfully pass the XML to the body.
Please let me know.
eg:
cy.readFile('Desktop/Testing/W1.xml')
.then(text1 => {
console.log(text1);
cy
.request({
url: 'my URL',
method: 'POST',
body: {text1},
headers: {
'Authorization':'Basic ........',
'content-type': 'application/......-v1.0+xml',
'Accept':'application/...v1.0+json,application/....-v1.0+json'
}
})
.then((response) => {
assert.equal(response.status, 200, "status was 200");
cy.log("Response Body",response.body);
console.log("Response Body",response.body);
})
})
I suggest something like this:
Prepare function for fetching XML
function fetchXML(text) {
return cy.request({
url: 'my URL',
method: 'POST',
body: text,
headers: { ... }
})
}
Then call readFile and pass to promise callback result
cy
.readFile('Desktop/Testing/W1.xml')
.then(text => fetchXML(text)) // or just .then(fetchXML)
.then(responseFromXML => { ... })
and i second callback you can use response from XML fetch
Link to docs about Cypress.Promise LINK

Http Post request in Angular JS

We are new to angular js.
We tried http request using $http.get it is working fine. But in post request it is creating an issue, it comes to success and show bad parameter error code 103.
Same we have tried in ajax request using $.ajax({}), and it is working fine.
I have also paste my code.
Can anyone help us out?
mainApp.controller('registrationCtrl', function($scope, $location, $http) {
$scope.registration = function() {
console.log("registration called");
var ws_url = "http://apparelinindia.com/selfiestandoff/WebServices/register";
var request = $http({
method: "post",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
dataType: 'json',
headers: {
'Content-Type': 'application/json'
}
});
request.success(function(data) {
console.log("Success" + data);
});
request.error(function(error) {
console.log("Success" + JSON.stringify(error));
});
};
});
You can use http Post in following way:
var request = $http.post(ws_url, {
user_email: $scope.email,
user_password: $scope.password
});
The name of the http method should be written in uppercase. Also, the property datatype is not awaited by $http, you should remove it:
var request = $http({
method: "POST",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
headers: {
'Content-Type': 'application/json'
}
});
Note, in the above call to $http you are setting the header 'Content-Type': 'application/json'. But this header is automatically injected by $http (see $http documentation), therefore you can remove it, and use the short syntax:
var request = $http.post(ws_url, data);
with data equals to:
{
user_email: $scope.email,
user_password: $scope.password
}
Are You Getting this error ??
{"status":false,"error":{"code":"103","message":"Required Parameters not found"}}
If Yes, Its Not your Problem Contact the Web service provider.
Ask him to give the valid parameter

Resources