protractor GET and PUT API call - api

I want to do API call in my protractor test case inside beforeAll() function and once I get the promise return my Test cases should start running. as my test cases are heavily dependent on API response.
I tried using jQuery however it is showing 'jQuery is undefined.' I am using protractor5.3.0.
var data ={
"request": {
"urlPattern": "/portal/user/profile",
"method": "GET",
"headers": {
"Accept": {
"contains": "application/json"
},
"Content-Type": {
"contains": "application/json"
}
}
},
"response": {
"bodyFileName": "abc.json",
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Origin": "{{request.headers.Origin}}"
},
"transformers": [
"response-template"
]
}
};
function setUserProfile(profile, data){
var id;
if(data) {
data.response.bodyFileName = "abc.json";
}
jQuery.ajax({
url: "someurl",
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function(result) {
result.mappings.forEach(function(mappingItem) {
if(mappingItem.request.urlPattern === '/portal/user/profile') {
id = mappingItem.id;
}
});
jQuery.ajax({
url: "someurl",
type: 'PUT',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json',
success: function(result) {
console.log("success?", result);
}
});
}
});
}
describe('Logout Page', function () {
var userDropdownEle;
beforeAll(function () {
request('someurl', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
userDropdownEle = element(by.css(logoutSelectors.dropDownButton));
xchangePageObject.getLoginUrl();
});
});

Related

How i can store an API body response and use it in other test on cypress?

I have this code to store response.body.address_id and use it in the next test but not working.
this is my hole code (two tests) :
`it('Create Address',function(){
return cy.request({
method:'POST',
url: `${Cypress.env('API_URL')}/address/api/v1/addresses`,
headers:{
Authorization : `${Cypress.env('access_token')}`,
"Content-Type": 'application/json',
},
body:{
"address_name": "Home",
"locality_area_street": "16th district",
"city": "DAKAR",
"country": "SENEGAL",
}}
).then((response)=>{
expect(response.status).to.eq(201)
Cypress.env('address_id', response.body.address_id);
})
})
it('Add Address',function(){
cy.request({
method:'PUT',
url: 'https://api/v1/cart/address',
headers:{
Authorization : `Bearer ${Cypress.env('access_token')}`,
"Content-Type": 'application/json',
},
body:{
"addressType": "BILLING",
"id": `${Cypress.env('address_id')}`
}}
).then((response)=>{
cy.log(Cypress.env('address_id'));
expect(response.status).to.eq(200)
})
})
})`
Can somme one help me to find a solution ?
You probably shouldn't use the Cypress.env for this,
Try this:
it("Create Address", function () {
return cy
.request({
method: "POST",
url: `${Cypress.env("API_URL")}/address/api/v1/addresses`,
headers: {
Authorization: `${Cypress.env("access_token")}`,
"Content-Type": "application/json",
},
body: {
address_name: "Home",
locality_area_street: "16th district",
city: "DAKAR",
country: "SENEGAL",
},
})
.then((response) => {
expect(response.status).to.eq(201);
Cypress.env("address_id", response.body.address_id);
this.address_id = response.body.address_id;
});
});
it("Add Address", function () {
cy.request({
method: "PUT",
url: "https://api/v1/cart/address",
headers: {
Authorization: `Bearer ${Cypress.env("access_token")}`,
"Content-Type": "application/json",
},
body: {
addressType: "BILLING",
id: this.address_id,
},
}).then((response) => {
cy.log(this.address_id);
expect(response.status).to.eq(200);
});
});

Simple axios call using wait and async works but when i put in in redux-thunk. it start giving errors in react native

import axios from 'axios'
export const loadData = (basicAuth, URL) => {
return (dispatch, getState) => {
dispatch({ type: 'LOGIN_START' })
axios.post(
URL,
null,
{ params: { 'email': 'zack', 'password': 'zack' } },
{
headers: {
"Content-Type":
"application/x-www-form-urlencoded; charset=UTF-8",
'Accept': "*/*",
'authorization': basicAuth,
"Access-Control-Allow-Credentials": true,
},
}
).then(function (response) {
dispatch({ type: 'LOGIN_SUCCESS', payload: response })
}).catch(function (error) {
dispatch({ type: 'LOGIN_FAILURE', payload: error })
})
}
}
When call this request in the main thread using wait and async it works but when i call it using this reduc-thunk it start giving errors.
{"DONE": 4, "HEADERS_RECEIVED": 2, "LOADING": 3, "OPENED": 1, "UNSENT": 0, "_aborted": false,
"_cachedResponse": undefined, "_hasError": true, "_headers": {"accept": "application/json,
text/plain, /", "content-type": "application/x-www-form-urlencoded"}, "_incrementalEvents":
false, "_lowerCaseResponseHeaders": {}, "_method": "POST", "_perfKey":
"network_XMLHttpRequest_Basic emFjazp6YWNr?email=zack&password=zack", "_performanceLogger":
{"_closed": false, "_extras": {}, "_pointExtras": {}, "_points": {"initializeCore_end":
1659600973109, "initializeCore_start": 1659600972966}, "_timespans":
{"network_XMLHttpRequest_Basic emFjazp6YWNr?email=zack&password=zack": [Object],
"network_XMLHttpRequest_http://10.0.2.2:8081/logs": [Object]}}, "_requestId": null,
"_response": "Expected URL scheme 'http' or 'https' but no colon was found", "_responseType":
"", "_sent": true, "_subscriptions": [], "_timedOut": false, "_trackingName": "unknown",
"_url": "Basic emFjazp6YWNr?email=zack&password=zack", "data": undefined, "readyState": 4,
"responseHeaders": undefined, "status": 0, "timeout": 0, "upload": {}, "withCredentials":
true}

Default content-type does not replace with new content-type (form-data) in axios in react native app for uploading image

I want to upload an image with axios in react native. This is my function which call upload image web service api:
function _uploadImgToServer(item) {
const file = {
uri: item.imgData.path,
type: item.imgData.mime,
name: 'ana' + item.imgId
}
const body = new FormData();
body.append('file', file);
console.log('uploadResult saga0', body)
dispatch(uploadImg({ body: JSON.stringify(body)}))
}
this is my axios config:
const instance = axios.create({
baseURL: '****',
responseType: 'json',
timeout: 10000,
headers: {
'WEB_TOKEN': '*****',
'UNIQUE_ID': '*****',
'UNIQUE_KEY': '*****',
Accept: "application/json",
'Content-Type': "multipart/form-data"
},
});
And I call my web service like bellow:
try {
const response = await instance.post(url, data);
return Promise.resolve(response.data);
} catch (error) {
return Promise.reject(error.response);
}
Part of the response I get in last part is:
'My log result' { data: { Code: 3, Message: 'Invalid Entry', Value: null },
status: 200,
statusText: undefined,
headers:
{
...
'content-type': 'application/json; charset=utf-8',
...
},
config:
{ url: 'upload',
method: 'post',
data: '{"_parts":[[{"uri":"file:///data/data/***packageName***/cache/react-native-image-crop-picker/IMG-20201222-WA0017.jpg","type":"image/jpeg","name":"ana_pu8kweg4e"},null]]}',
headers:
{ Accept: 'application/json',
'Content-Type': 'multipart/form-data',
WEB_TOKEN: '*****',
UNIQUE_ID: '****',
UNIQUE_KEY: '****' },
baseURL: '****',
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 10000,
adapter: [Function: xhrAdapter],
responseType: 'json',
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: [Function: validateStatus] },
...
}
As you see in my log result, the content-type in header I have sent is 'multipart/form-data' but server has received 'application/json; charset=utf-8' so I cannot upload my image.
It is worth to mention that if I do not use JSON.stringify, content-type will not be sent at all. I have searched a lot but I could not find any useful response.
I found that my problem was not about "content-type" at all. I had to put image type at the end of the image name.
const file = {
uri: item.imgData.path,
type: item.imgData.mime,
name: 'ana'+item.imgId+'.jpeg'
}
I've just added '.jpeg' at the end of the name. I think it is depended on the backend programmer coding algorithm and It cannot cause problem always.

React Native fetch() not outputting body in console log

I am using fetch() to get some data from an API. When testing in Postman the data is returned successfully as JSON. However, when testing from react native app on android I get a text/html response, not sure why. How can I view the body of the response from the text in console.log() to debug? When I do console.log(resp) I can not see the body.
const response = await fetch('https://web.com/api/usersignup', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(resp => {
this.setState({spinner: false});
console.log(resp);// output in console is pasted under this code
return resp.text();
//return resp.json();
})
.then((responseJson) => {
console.log(responseJson);
})
.catch(error => {
this.setState({spinner: false});
Alert.alert('Error', error.message);
throw error;
});
Output I get in Metro Builder when using console.log(). Does not include body.
Response {
"_bodyBlob": Blob {
"_data": Object {
"blobId": "63acc7d8-bd8a-4dd7-b33b-f0e4f202f97e",
"offset": 0,
"size": 0,
},
},
"_bodyInit": Blob {
"_data": Object {
"blobId": "63acc7d8-bd8a-4dd7-b33b-f0e4f202f97e",
"offset": 0,
"size": 0,
},
},
"headers": Headers {
"map": Object {
"cache-control": "public, max-age=0",
"connection": "keep-alive",
"content-length": "0",
"content-type": "text/html; charset=UTF-8",
"date": "Sat, 09 Nov 2019 21:06:05 GMT",
"server": "Apache",
"x-ratelimit-limit": "60",
"x-ratelimit-remaining": "59",
},
},
"ok": true,
"status": 200,
"statusText": undefined,
"type": "default",
"url": "https://web.com/api/usersignup",
}
You cannot print the body until the promise of first then is finished.
I made an example with your code: https://snack.expo.io/#egizas/fetch-print-body
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//body: JSON.stringify(formData)
})
.then(resp => {
console.log('Printing out not json');
console.log(resp);
return resp.json();
})
.then((responseJson) => {
console.log('Printing out json');
console.log(responseJson);
})
.catch(error => {
this.setState({spinner: false});
Alert.alert('Error', error.message);
throw error;
});
Just replace the endpoint and provide correct header.

Vue firing requests one after another

I have two functions. I would like to fire a function - wait until firstFunction() has ended and then fire secondFunction(). But I don't want to do this as a callback.
firstFunction() {
this.$http.post(
`url1`,
data1,
{ channel: 'default' },
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
).then(response => {
console.log(response)
});
},
secondFunction() {
this.$http.post(
`url2`,
data2,
{ channel: 'default' },
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
).then(response => {
console.log(response)
});
},
finalFunction() {
this.firstFunction()
this.secondFunction()
}