I have the following test
let rxId = "";
let basketAuthToken = "";
let basketId = "";
let replacedBody = "";
cy.fixture(`payload/${ordersPostPayload}`).then((Body) => {
cy.readFile(`temp/resultIdFile.json`).then((resultIdFile) => {
Id = resultIdFile.lastSucceededRxId;
basketAuthToken = resultIdFile.baskets[0].authToken;
basketId = resultIdFile.baskets[0].basketId;
cy.log(`the value of the read value is ${Id}`);
replacedBody = JSON.stringify(Body).split(`$Id`).join(Id);
cy.writeFile(`temp/ordersPostPayload.json`, replacedBody);
cy.request({
method: "POST",
url: `https://***/ops/orders`,
headers: {
"Content-Type": "application/json",
Channel: "**",
"EsbApi-Subscription-Key": `****`,
"Accept-Language": `en-US`,
"basket-token": basketAuthToken,
"basket-id": basketId,
redirectUrl: "****/evaluate-payment",
cancelUrl: "****/evaluate-payment",
},
body: replacedBody,
failOnStatusCode: false,
}).then((response) => {
cy.writeFile("temp/result.json", response);
});
});
});
The request is sent to the backend. On cypress GUI the request is just fired once. but when I check the backend I can see two requests.
Related
I am writing API tests using Cypress 6.4.0 & TypeScript where I need to upload a pdf file in the request body.
My code for the request is:
My code for the request body is:
public async createAssetDocTest() {
let url = sharedData.createAsset_url + sharedData.assetA;
let response = await fetch(url
,
{
method: 'POST',
body: await requestbody.createAssetDocBody(),
headers: {
Authorization: sharedData.bearer + " " + adminTokenValue,
Accept: sharedData.accept,
'Content-type': sharedData.docReqContent,
},
}
);
expect(response.status).to.equal(200);
public async createAssetDocBody(): Promise<any> {
const file = sharedData.doc;
cy.fixture(file).then((pdfDoc) => {
Cypress.Blob.binaryStringToBlob(
pdfDoc,
sharedData.contentTypeValue
).then(async (blob: string | Blob) => {
const formData = new FormData();
formData.set(sharedData.document, blob, file);
const body = {
formdata: {
document: {
value: pdfDoc,
options: {
filename: sharedData.document,
contentType: null,
},
},
},
};
return body;
});
});
}
However, the file does not upload the file & the request fails with error 400. Is there a better way to upload files in the body of the POST request?
enter image description here
Resolved this issue!
The main issue was that my Cypress version was too old. Upgraded to 9.7.0
Then added the following code:
public async createAssetDoc(): Promise<any> {
cy.fixture("pic location", "binary")
.then((file) => Cypress.Blob.binaryStringToBlob(file))
.then((blob) => {
var formdata = new FormData();
formdata.append("document", blob, "pic location");
const url = "your url";
cy.request({
url,
method: "POST",
body: formdata,
headers: {
Authorization:
"bearer" + " " + token,
Accept: "application/json",
"Content-Type": "multipart/form-data",
},
}).then((response) => {
expect(response.status).to.equal(201);
expect(response.statusText).to.equal(
sharedData.fileUploadStatusText
);
const finalResponse = String.fromCharCode.apply(
null,
new Uint8Array(response.body)
);
return finalResponse;
});
});
}
I would like to use Cypress for API testing. My goal is to extract a part of the API response and pass it to another API request. Here's a sample code:
Cypress.Commands.add('createCustomer', () => {
return cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
}).then((response) => {
return new Promise(resolve => {
expect(response).property('status').to.equal(201)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const jsonData = response.body;
const memberId = jsonData.id
resolve(memberId)
return memberId
})
})
})
With this code, I am getting [object%20Object] as the result.
Hoping for some feedback.
So you are adding the id generated by the POST to a subsequent GET request?
Try returning the id without using a Promise, I don't think you need one at that point since the response has already arrived.
}).then((response) => {
expect(response).property('status').to.equal(201)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const jsonData = response.body;
const memberId = jsonData.id;
return memberId;
})
Url for GET
cy.createCustomer().then(id => {
const url = `api/v1/Customers${id}`;
...
or
cy.createCustomer().then($id => {
const id = $id[0]; // Not quite sure of the format, you may need to "unwrap" it
const url = `api/v1/Customers${id}`;
...
If you want to pass response from API Request 1 to API Request 2, you can do something like this:
describe('Example to demonstrate API Chaining in Cypress', function () {
it('Chain two API requests and validate the response', () => {
//Part 1
cy.request({
method: 'GET',
url: 'https://www.metaweather.com/api/location/search/?query=sn',
}).then((response) => {
const location = response.body[0].title
return location
})
//Part 2
.then((location) => {
cy.request({
method: 'GET',
url: 'https://www.metaweather.com/api/location/search/?query=' + location
}).then((response) => {
expect(response.status).to.eq(200)
expect(response.body[0]).to.have.property('title', location)
})
})
})
})
Your code seems to be failing during the initial request, not during the subsequent actions. I am far from a Javascript expert, but you seem to have some unnecessary complexity in there. Try simplifying your command like this and see if you can at least get a successful request to go through:
Cypress.Commands.add('createCustomer', () => {
cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
})
})
And if that works, keep going:
Cypress.Commands.add('createCustomer', () => {
cy.request({
method: 'POST',
url: 'api/v1/Customers',
headers: {
'Content-Type': 'application/json'
},
body: {
// sample content
}
}).then((response) => {
expect(response).property('status').to.equal(201)
expect(response.body).property('id').to.not.be.oneOf([null, ""])
const jsonData = response.body;
const memberId = jsonData.id
return memberId
})
})
i have some troubles with imgur api. I converted image to base64 code and tried upload it to imgur api. Unfortuatelly I'm receiving an error:
"error": "Invalid URL (data:image/png;base64,iVBORw0KGgoAA..."
Here's my function:
uploadImageToImgur: function (file) {
const url = 'https://api.imgur.com/3/image',
reader = new FileReader();
reader.onloadend = async function () {
let { result } = reader;
try {
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'my client key',
},
body: result
});
const response = await request.json();
console.log(response);
} catch (e) {
throw new Error(e);
}
}
if (file) {
reader.readAsDataURL(file);
}
}
You need to cut this part out.
You are missing some parameters. Also, make sure your headers have the Client-ID key.
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'Client-ID {yourKey}',
},
form: {
"image": result,
"type": "base64"
}
});
Still learning on RN... I'm trying to use fetch() in react-native to get a specific data from my server, before opening a webpage in smartphone's browser.
Here is what I wrote :
openLink = () => { //Communicate to the server to get an unique key_id
this.state = {urlKey: 'text'}; //Initial state
var params = {
// Some params send by POST to authenticate the request...
};
var formData = new FormData();
for (var k in params) {
formData.append(k, params[k]);
}
fetch(Constants.URL.root+"mobile/authorize_view", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({urlKey:responseJson.document_key}); //Getting the response, and changing the initial state (was 'text' previously)
})
.done();
var urlString = Constants.URL.upload + '/' + this.state.urlKey; // !!Problem : opening in browser with this.state.urlKey = text, and not document_key!!
Linking.canOpenURL(urlString).then(supported => {
if (supported) {
Linking.openURL(urlString);
} else {
console.log('Don\'t know how to open URI: ' + this.props.url);
}
});
}
Actually, as you can see, I ask for a specific key to my server (urlKey, that is returned in a JSON Object : responseJson.document_key).
Everything is running well in server's part, cause I put this generated document_key in my Database, and I can see it is put correctly.
The problem is in React-native part : the browser opens a webpage with this.state.urlKey as **text** which is the initial state that the function fetch should have turned into the document_key sent by server...
What am I missing ?
The fetch statement is asynchronous. Meaning when you call fetch then next line of execution not necessary the .then but is
var urlString = Constants.URL.upload + '/' + this.state.urlKey;
Note by this stage if .then isnt complete fetching the data your this.state.document_key will not be populated. Hence why you see the error
Instead move that code in the final then e.g:
openLink = () => { //Communicate to the server to get an unique key_id
this.state = {urlKey: 'text'}; //Initial state
var params = {
// Some params send by POST to authenticate the request...
};
var formData = new FormData();
for (var k in params) {
formData.append(k, params[k]);
}
fetch(Constants.URL.root+"mobile/authorize_view", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({urlKey:responseJson.document_key}); //Getting the response, and changing the initial state (was 'text' previously)
//moved inside then
var urlString = Constants.URL.upload + '/' + this.state.urlKey; // !!Problem : opening in browser with this.state.urlKey = text, and not document_key!!
Linking.canOpenURL(urlString).then(supported => {
if (supported) {
Linking.openURL(urlString);
} else {
console.log('Don\'t know how to open URI: ' + this.props.url);
}
});
})
.done();
}
I am trying to implement antiforgerytoken in my project. I am able to implement it when making ajax call below.
function docDelete(id) {
var _upload_id = $("#docId").val();
var _comments = $("#name").val();
var forgeryId = $("#forgeryToken").val();
$("#dialog-form").dialog("open");
$.ajax({
type: 'GET',
cache: false,
url: '/DeleteDocument/Delete',
dataType: 'json',
headers: {
'VerificationToken': forgeryId
},
data: { _upload_id: _upload_id, _comments: _comments },
success: function (data) {
$('#dialog-form').dialog('close');
$('#name').val('');
$('#dvSuccess').val(data);
Getgridata(data);
}
});
}
above code works fine. But in some cases i am making ajax request as below.
var forgeryId = $("#forgeryToken").val();
function GetGrid() {
$.ajax(
{
type: "GET",
dataType: "html",
cache: false,
url: '/Dashboard/GetGridData',
headers: {
'VerificationToken': forgeryId
},
success: function (data) {
$('#dvmyDocuments').html("");
$('#dvmyDocuments').html(data);
}
});
}
Above code does not send any token to below method.
private void ValidateRequestHeader(HttpRequestBase request)
{
string cookieToken = string.Empty;
string formToken = string.Empty;
string tokenValue = request.Headers["VerificationToken"]; // read the header key and validate the tokens.
if (!string.IsNullOrEmpty(tokenValue))
{
string[] tokens = tokenValue.Split(',');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken); // this validates the request token.
}
}
In layout.cshtml i have implmented code to get token.
<script>
#functions{
public string GetAntiForgeryToken()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + "," + formToken;
}
}
</script>
<input type="hidden" id="forgeryToken" value="#GetAntiForgeryToken()" />
The variable tokenValue catching null each time. So what i understood is through headers i am not able to send token value. I tried many alternatives. So anyone suggest me how can i overcome this issue? Thank you in advance.
I tried as below still i am getting null value.
var token = $('[name=__RequestVerificationToken]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
alert(token);
var forgeryId = JSON.stringify($("#forgeryToken").val());
function GetGrid() {
$.ajax(
{
type: "GET",
dataType: "html",
cache: false,
url: '/Dashboard/GetGridData',
cache: false,
headers: headers,
success: function (data) {
$('#dvmyDocuments').html("");
$('#dvmyDocuments').html(data);
}
});
}