Need to write testcase for below action.jsx class.How to write test case having headers.
export function getDeliveryDetail() {
return (dispatch, getState) => {
let createModalDescription = "";
let token = getState().auth.token;
let deliverOrderId = getState().reprocess.deliveryOrderId;
if (deliverOrderId) {
const headers = {
headers: {
"Content-type": "application/json",
Accept: "application/json",
Authorization: `Bearer ${token}`
},
correspondenceAxios()
.get("/delivery-orders/" + deliverOrderId, headers)
.then(deliveryResponse => {
dispatch({
type: ACTION_TYPES.DELIVERY_ORDER_DETAIL,
payload: JSON.stringify(deliveryResponse.data, null, " ")
});
})
Need to write testcase for above action.jsx class.
Related
We are using Axios along with react query. Can someone point me to correct example, so that all the react query keys like isError, isSuccess is properly set. As, I read through other answers, the catch block below might be the culprit.
function api<TResponse>({
method,
url,
body,
contentType = 'application/json',
}: IAccessInterceptor): Promise<TResponse> {
return new Promise((resolve, reject) => {
const payload: AxiosRequestConfig = {
method,
url,
headers: {
Accept: contentType,
'content-type': contentType,
},
};
// including 'data' if body is not null
if (body != null) {
payload.data = body;
}
axios(payload)
.then((response: { data: { message: TResponse; data: TResponse } }) => {
resolve(response.data?.message || response.data?.data);
})
.catch((error: { response: { data: IServerError } }) => {
reject(error?.response?.data);
});
});
}
// Some problem in above catch block.
const getABC = (
id: string,
): Promise<IABC> => {
const method = 'GET';
const url = `${BASE_URL}.get_abc?assignment_id=${assignmentId}`;
return api<IABC>({ method, url });
};
export const useABC = (
assignmentId: string | null,
): UseQueryResult<IABC> =>
useQuery<IABC, Error>(
queryKeys.getABC(id),
() => someFunction(id|| ''),
{ enabled: !!id},
);
"useABC().isError" is always false
I have a simple app with two routes, which I use locally and on IBM Cloud/Cloud Foundry (512 M RAM)
/
returns "Hello World!" & 200 locally and on the IBM Cloud
/getData
returns some data locally & 200
on cloud it returns 400, no logs
Edit:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
var cors = require("cors"); // Cors
app.use(cors());
var port = process.env.PORT || 3000;
app.get('/', (req, res) => res.send('Hello World!'))
// *************** GETDATA ***************************************
app.get('/getData', function (req, res) {
var request = require("request");
var httpHeaderOptions = {
accept: "application/json",
"content-type": "application/json",
apikey: req.headers.apikey
};
var restoptions = {
method: "GET",
url: req.headers.route,
headers: httpHeaderOptions
};
// console.log("headers: " + JSON.stringify(req.headers));
// console.log("GET DOCS: \n", JSON.stringify(restoptions));
request(restoptions, function (error, response, body) {
console.log(typeof (body));
body_json = JSON.parse(body);
if (error) {
console.error("Failed: %s", error.message);
body = {
"error": error.message
};
res.status(400).json(body);
} else {
console.log("Success: \n", body);
res.status(200).json(body_json);
}
});
});
// *************** POST DOC ***************************************
app.post('/postData', function (req, res) {
var request = require("request");
var httpHeaderOptions = {
accept: "application/json",
"content-type": "application/json",
apikey: req.headers.apikey
};
var restoptions = {
method: "POST",
url: req.headers.route,
headers: httpHeaderOptions,
body: req.body,
json: true
};
console.log("headers: " + JSON.stringify(req.headers));
console.log("POST DOC: \n", JSON.stringify(restoptions));
request(restoptions, function (error, response, body) {
if (typeof (body) == 'object' && Object.keys(body).length === 0) {
// unknown error, empty resposne
res.status(400).json(body);
} else {
console.log("body: " + JSON.stringify(body));
if (error) {
console.error("Failed: %s", error.message);
body = {
"error": error.message
};
res.status(400).json(body);
} else {
console.log("Success: \n", JSON.stringify(body));
res.status(200).json(body);
}
}
});
});
// *********************
app.post('/watsonAssistant', function (req, res) {
var request = require("request");
var reqURL = "https://hackathon-jps.eu-de.mybluemix.net/watsonAssistant";
console.log("URL: \n", reqURL);
console.log("POST Body: \n", JSON.stringify(req.body));
var httpHeaderOptions = {
accept: "application/json",
"content-type": "application/json",
};
var restoptions = {
method: "POST",
url: reqURL,
headers: httpHeaderOptions,
body: req.body,
json: true
};
console.log("send request \n");
request(restoptions, function (error, response, body) {
console.log("in request \n");
if (error) {
console.error("Failed: %s", error.message);
body = {
"error": error.message
};
res.status(400).json(body);
} else {
console.log("Success: \n", body[0]);
res.status(200).json(body[0]);
}
});
});
// Start the server
app.listen(port, function () {
console.log('simple forward server is running')
});
link to the code
This will be because whatever req.headers.route is set to, is not visible to the app when it is running in the cloud. Your first check should be on error. Your second check should be if body is not null, and an object instead you immediately JSON.parse body, which may be throwing a parsing exception.
I am attempting to make a http.post call with angular 2. I have tested the call in postman, so I know that the api is working. I get an error, input empty which means that it isn't getting the data. I've read a few answers and articles, but not able to make a successful call with the data.
Can anyone give me some insight into what I am missing?
public upload(name: string, data: any, result, contentType: string) : Promise<Response> {
let headers = new Headers({ 'Content-Type': contentType });
let options = new RequestOptions({ headers: headers });
return this.http
.post(this.urlAPI, data, options)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
extractData(res:Response) {
console.log('res: ', res);
let body = res.json();
return Promise.resolve(res);
}
handleError(err: any): Promise<any> {
console.error('An Error has occured: ', err);
return Promise.reject(err);
}
I am not sure what is the type of your 'data'. Data has to be stringified before sent. Below is a workable version for me.
saveNote(note: ApprovalNoteModel): Observable<ApprovalNoteModel> {
let body = JSON.stringify(note);
let headers = this.utilsSvc.getAuthHeaders();
headers.set('Content-Type', 'application/json');
return this.http.post('cloud/api/approval/note', body,
{ headers: headers }
).map(response => response.json());
}
If it is a file, then you can not do that thru 'http', I believe. Here is my workable version.
addFileRequest(referenceId: number, licenseId: number, url: string, files: File[]): Observable<any> {
return Observable.create(observer => {
this.progressObserver = observer;
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
formData.append('referenceId', referenceId);
formData.append('licenseId', licenseId);
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(xhr.response);
observer.complete();
} else {
if (xhr.response.status)
observer.error(xhr.response);
else
observer.error({ 'status': xhr.status, '_body': xhr.response });
}
}
};
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.setRequestHeader('Authorization', this.utilsSvc.getToken());
xhr.send(formData);
});
}
I have setup steps before running my e2e test in which I have to create users before I execute my test. I am using Protractor's Request API to make REST API POST calls but I'm not sure how can I pass data (body) and headers in the request. My request should look like this:
URL : 'rest/users', Headers : {'Content-Type' : 'application/json'}, body: {"userName": "user1", "domain": "1", "password": "password1", "userID": "1"}
I am trying to do something like this:
var request = require('request');
function createuser(url){
console.log("complete url = ", browser.baseUrl+url);
request({
method: 'POST',
uri: browser.baseUrl+url,
multipart: [
{'Content-Type': 'application/json'},
{body: {
'userName': 'test3',
'tenantKey': '0',
'password': 'Test3',
'userID': '3'}
}
],
function(error, response, body) {
if (error) {
return console.error('User Creation failed:', error);
}
console.log('User Creation successful! Server responded with:', body);
}
})
};
createuser('rest/1.0/dev/users');
It's throwing the following error (I'm not sure what am I doing wrong):
Error: Body attribute missing in multipart.
Stack:
Error: Body attribute missing in multipart.
at C:\code\ui\dgui\node_modules\request\lib\multipart.js:35:36
at Array.forEach (native)
at Multipart.isChunked (C:\code\ui\dgui\node_modules\request\lib\multipart.js:33:11)
at Multipart.onRequest (C:\code\ui\dgui\node_modules\request\lib\multipart.js:104:22)
at Request.multipart (C:\code\ui\dgui\node_modules\request\request.js:1176:19)
at Request.init (C:\code\ui\dgui\node_modules\request\request.js:424:10)
at new Request (C:\code\ui\dgui\node_modules\request\request.js:142:8)
at request (C:\code\ui\dgui\node_modules\request\index.js:55:10)
at createuser (C:\code\ui\dgui\tests\e2e\TestSuites\_BVT\_CreateNewUsers2.js:36:2)
at Suite.<anonymous> (C:\code\ui\dgui\tests\e2e\TestSuites\_BVT\_CreateNewUsers2.js:49:3)
I am able to achieve this using 'superagent', this is how I am using:
CallRestAPI:
var request = require( "superagent" );
var PostUrl = browser.baseUrl + 'rest/1.0/dev/users';
exports.CreateUsers = function(body){
console.log("Executing CreateUsers");
var data = '{' +body + '}';
console.log("Send data in post request = ", data);
request.post( PostUrl ).set('Content-Type', 'application/json').send(data).end(function(err,res){
if(err){
console.log("CreateUsers post error= ", err )
} else{
console.log("CreateUsers post response = ", res.status)
}
});
};
Using this Function as:
var Common = require('../.././helpers/CallRestAPI');
Common.CreateUsers('"userName": "test1", "tenantKey": "0", "password": "Test1", "userID": "1"');
Have managed it in my code with request validation when eg. access token is wrong or app do not respond. Imo it's better approach because your proposition always passes test what can give false positive.
exports.authorize = function (login, pass) {
var action = function () {
return getToken().then(function (token) {
var dfd = protractor.promise.defer();
req.post(getBackendUrl() + '/authorize/authenticate')
.set('Content-Type', 'application/json').set('RequestId', uuid.v4()).set('Authorization', token)
.send({"login": login, "pass": pass})
.end(function (err, res) {
if (err) {
dfd.reject(res)
} else {
dfd.fulfill(res.body);
}
});
return dfd.promise;
})
};
return browser.controlFlow().execute(action);
};
Endpoint authorize returns 200 status code for both - valid and not valid credentials so in specific test it can be distincted by simple jasmine expect like:
var Initialize = require('..initialize');
var successResponse = {status: 'success'};
expect(Initialize.authorize('some_login', 'some_password')).toEqual(successResponse);
var request = require('request');
var options = {
method: 'POST',
url: 'https://sbx-office-api.b2bcloud.com/rmi/v1/books/list?type=fetchall',
headers: {
'Accept': 'application/json, text/plain, */*',
'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlFrTTFRemt6UlVJNE5UazNSVVJGTUVVNU5rTXlNVVpFT0RJek5EQTNPRFkyTVVaRVFrVXdSZyJ9.eyJodHRwczovL21hcnZlbC5zaGFycC5jb20vdGVuYW50aWQiOiJkNTA4Yjc3NC01NjBlLTRlNTktYTk3Yy1mODQxYjhmYjVkN2QiLCJodHRwczovL21hcnZlbC5zaGFycC5jb20vY29ubmVjdGlvbiI6InNoYXJwc29mdHdhcmVkZXYtd2FhZCIsImh0dHBzOi8vbWFydmVsLnNoYXJwLmNvbS9lbWFpbCI6InJhbWVzaHRAU2hhcnBzb2Z0d2FyZWRldi5vbm1pY3Jvc29mdC5jb20iLCJodHRwczovL21hcnZlbC5zaGFycC5jb20vbmFtZSI6IlJhbWVzaCBUIiwiaHR0cHM6Ly9tYXJ2ZWwuc2hhcnAuY29tL3JvbGUiOiJCQSB1c2VyIiwiaXNzIjoiaHR0cHM6Ly9zYnguYXV0aDAuY29tLyIsInN1YiI6IndhYWR8VGVFbVNzNGpnRGpXeTRVX0ItWlo4SDRobFZielVUdzM4djNmb2MzNXVzWSIsImF1ZCI6WyJodHRwczovL3NieC5hdXRoMC5jb20vYXBpL3YyLyIsImh0dHBzOi8vc2J4LmF1dGgwLmNvbS91c2VyaW5mbyJdLCJpYXQiOjE1NjY5NzY4MzIsImV4cCI6MTU2Njk4NDAzMiwiYXpwIjoiQW1zeU9UbHI3akg5eFU5azZlem15ODJNZDV4NDUyZFIiLCJzY29wZSI6Im9wZW5pZCBwcm9maWxlIn0.D5MoBVJ2lWZ7b3FCZtMQkmdMxJot8SCR1-Oso-wponPtF2y6kLxKK5dUftI_yzydvaJsZ9mwjVvZIAHESlrwkjVizYGXTFchjasT81hMZtJgt6iW8sA7Nu5qx7MVsc2z7UAS0mGhV2a_NEvZaYQ1A0dC19wG2A6bNJIMNEy46oJXlUe8nxb1ezkh4CkO3jUnVIPBo4rney_uwcXj-wc5hiE3a6m7jeHphyy70zDBFD_YRiizZaXzI-LTPGvhuRb7UtfcZuOomQqOuH6xebaoe3OzX9aA7CfWCHIJDhjQJwC-5BR5HQ9k7FCae3L4pWfmUVUOTZEFViJtxazLxOjM_w',
'Content-Type':'application/json',
'Sec-Fetch-Mode': 'cors',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36'
},
body: '{ "headers":{"normalizedNames":{},"lazyUpdate":null}}'
};
it('Should reach testsite', done => {
request(options, function (error, response, body) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
done();
});
});
I don't understand what I am doing wrong, my server returns "undefined" when I try to get the json.
POST(url, data) {
var headers = new Headers(), authtoken = localStorage.getItem('authtoken');
headers.append("Content-Type", 'application/json');
if (authtoken) {
headers.append("Authorization", 'Token ' + authtoken)
}
headers.append("Accept", 'application/json');
var requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: this.apiURL + url,
headers: headers,
body: data
})
return this.http.request(new Request(requestoptions))
.map((res: Response) => {
if (res) {
return { status: res.status, json: res.json() }
}
});
}
And my function:
login(username, password) {
this.POST('login/', {test: 'test'}).subscribe(data => {
console.log(data)
})
}
When I try this, the request body looks like this:
So instead of sending actual json, it just sends "[object Object]".
Instead of "Request payload" it should be "JSON". What am I doing wrong?
I have been looking for a visual answer to the question of posting json data in Angular for a while, to no avail. Now that I eventually have something working, let's share:
Inlined
Let's assume you expect a json response body of type T.
const options = {headers: {'Content-Type': 'application/json'}};
this.http.post<T>(url, JSON.stringify(data), options).subscribe(
(t: T) => console.info(JSON.stringify(t))
);
Official doc
Extendable class
import { HttpClient, HttpHeaders } from '#angular/common/http';
export class MyHttpService {
constructor(protected http: HttpClient) {}
headers = new HttpHeaders({
'Content-Type': 'application/json'
});
postJson<T>(url: string, data: any): Observable<T> {
return this.http.post<T>(
url,
JSON.stringify(data),
{headers: this.headers}
)
}
The gist
In the beginning I missed this sort of 'nested' way to pass in the content-type:
{headers:{'Content-Type': 'application/json'}}
You need to stringify the payload
var requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: this.apiURL + url,
headers: headers,
body: JSON.stringify(data)
})
The header should be
'Content-Type': 'application/json'
and
body: data
should be
body: JSON.stringify(data);