Cypress intercept API JSON response and extract URL - json

My web app sends an API POST request to create an application and returns JSON response. I want to access one particular JSON object from that response.
My JSON starts like this
[
{
"status_code": 201,
"body": {
"created": "2021-01-28T00:00:00Z",
"modified": "2021-01-28T00:00:00Z",
"id": "a2d86d17-9b3c-4c4d-ac49-5b9d8f6d6f8f",
"applicant": {
"id": "07f1e1d3-0521-401b-813e-3f777f2673c6",
"status": "Pending",
"first_name": "",
"last_name": "",
"URL": "some onboarding url"
And I wanna take that URL in the JSON response and visit it later in my cypress automation script.
Notice that the JSON repsonse starts with a square bracket not a curly bracket, which means, the whole response is an object, I assume?
My cypress script looks like this
cy.contains('button', 'CONTINUE').click()
cy.EmailGen('candidate').then(email => {
cy.get('#emails\\[0\\]').type(`${email}`)
cy.wrap(email).as('candidateEmail')
})
//writing intercept here, before the Send application button, which triggers the POST req.
cy.intercept('/hr/v1/applications/invite').as('getURL')
cy.get('button').contains('SEND APPLICATION').click({ force: true })
//waiting on the alias of intercept and using interception to print objects from response
cy.wait('#getURL').then((interception)=> {
cy.log(interception.response.body.applicant.URL)
})
cy.Logout()
The script executes with no errors. Just that nothing is logged in the cy.log statement. Below is the screen.
I also tried using another method as given below.
cy.intercept('/hr/v1/applications/invite',(req) => {
req.reply((res=> {
expect(res.status_code).to.equal('201')
expect(res.body.applicant.status).to.equal('Pending')
}))
})
In this case, I get a assert error embedded with the request and response along with some other stuff which I am unable to understand.
The complete error goes something like this...
"expected The following error originated from your test code, not from Cypress.\n\n > A response callback passed to req.reply() threw an error while intercepting a response:\n\nexpected undefined to equal '201'\n\nRoute: {\n "matchUrlAgainstPath": true,\n "url": "/hr/v1/applications/invite"\n}\n\nIntercepted request:{} Intercepted response: {} When Cypress detects uncaught errors originating from your test code it will automatically fail the current test. to include window.zE is not a function"
Its a bit weird to read this..
My application sometimes throws this exception, which I have handled using following code.
cy.on('uncaught:exception', (err, runnable) => {
expect(err.message).to.include('window.zE is not a function')
done()
return false
})
I really hope I have explained everything here. Please, help a noob.
Regards

As Richard Matsen suggested in the comments,
I used console.log(interception.response) and checked the console output in the browser controlled by Cypress.
I Noticed that the response json structure was something different than what I got in the network tab of developers tools, while using the web app.
The response was something like below...
{headers: {…}, url: "https://example.com/hr/v1/applications/invite/batch/", method: null, httpVersion: "1.1", statusCode: 200, …}
body: Array(1)
0:
body:
applicant: {id: "c6b2d686-d4f3-483e-abc8-e4641c365845", status: "Pending", first_name: "", last_name: "", email: "qa2+candidate879#example.com", …}
applicant_status: "NONE"
applicant_status_label: "None"
created: "2021-01-29T00:00:00Z"
get_applicant_status_display: "None"
id: "ad2939f5-c8ab-490a-a9e1-b0474de69e2c"
URL: "some url"
This made me modify the json traverse to
interception.response.body[0].body.applicant.URL
If others have a neat way to handle this, please let me know!

Related

AWS API Gateway VTL Include Source API JSON in Response Template

We would like to include the Integration/Source API JSON in the response, but when we attempt to include the Object, it does not encode properly.
"success": true,
"message": "Resource Call Made Successfully",
"data": {ip=127.0.0.1, ipv4=127.0.0.1, ipv6=0:0:0:0:0:0:0:0, asn=null, asn_name=null, country=US, useragent={family=Other...
As you can see, the strings lose their quotes; breaking the JSON. Here's the template;
#set($inputRoot = $input.path("$"))
{
"success": true,
"message": "Resource Call Made Successfully",
"data": $inputRoot
}
I've tried using $json.parse(), escaping, etc with no luck. Anyone familiar enough to give some direction on how to stringify this so I can include it in the response?
Use syntax like below,
"subject": "$util.escapeJavaScript($input.path('$.Attributes.subject.S')).replaceAll(\"\\\\'\",\"'\")"
It's an explanation in $util.escapeJavaScript() function

"status_code": 422, "error_code": "REQUEST_PARAM_PARSE", "detail": "The 'data' parameter must be a list"

I’m using the HTTP Request Wizard to set up a POST request to MonkeyLearn. This endpoint expects a JSON in the request body (or payload body). It must be an object with the data property and a list of the texts you want to classify as value. For example:
{
"data": [
"This is the best sentiment analysis tool ever!!!",
]
}
So, in the HTTP Request Wizard, I set up under Parameters:
Name: data
Value: "This is the best sentiment analysis tool evert!!!"
Type: GetorPost
However, in the preview response I get:
{
"status_code": 422,
"error_code": "REQUEST_PARAM_PARSE",
"detail": "The ‘data’ parameter must be a list"
}
I can’t figure out what list the endpoint expect?
I am not familiar with the "HTTP Request Wizard" and cannot find it either. But from what you've written it is clear that you are sending a string and not an array of strings. You value should look like this: Value: [ "This is the best sentiment analysis tool evert!!!" ]

Zapier Catch (Raw) Hook JSON parsing issue

I would like to configure sync between two different CRMs (Clevertap and Intercom) using Zapier and Webhooks. In general Clevertap sends the following JSON to webhook:
{
"targetId": 1548328164,
"profiles": [
{
"event_properties": {
"MSG-sms": true,
"MSG-push": true,
"businessRole": "EMPLOYEE",
"Mobile Number": "123123123123",
"Name": "Artem Hovtvianisa",
"Title": "Mr",
"Last Name": "Hovtvianisa",
"Gender": "M",
"Customer type": "Business Account Holder",
"MSG-email": true,
"First Name": "Artem",
"Last seen IP": "111.177.74.50",
"tz": "GMT+0200",
"International customer": "yes",
"isBusiness": true,
"Email": "xxxyyy#gmail.com",
"Identity": 15675
},
"objectId": "e32e4de3c1e84b2d9bab3707c92cd092",
"all_identities": [
"15675",
"xxxyyy#gmail.com"
],
"email": "xxxyyy#gmail.com",
"identity": "15675"
}
]
}
Zapier provides two types of catch webhook: regular and Raw.
Catch Raw Hook
When I use this type, JSON raw data will be handled OK and on the next step (Zapier JS code app) I am able to pass proper JSON data like in example above.
However when I use simple JS code to parse JSON object and get profiles[0] array value I get the following error "TypeError: Cannot read property '0' of undefined"
JS Code from Code step:
var result = JSON.parse(JSON.stringify(inputData));
console.log(result.profiles[0]);
return result;
Catch Hook
In case I use regular Catch Hook, hook parse data in some odd way, like this:
JSON.parse cannot recognize this structure.
Please advise how can I handle Webhook Zapier step in a proper way in order to get profiles[0] array item values?
Thanks in advance!
David here, from the Zapier Platform team. You're on the right track!
Catch Raw Hook is the way to go here. Your issue is that the data is coming in as a string and you're re-stringifying it before parsing it, which gets you back to where you came from. A simpler version:
JSON.stringify("asdf") // => "\"asdf\"", quotes in the string
JSON.parse("\"asdf\"") // => "asdf", the original string
"asdf".profiles // => undefined
undefined[0] // => error, cannot read property "0" of undefined
Instead, just parse it and you're good to go!
// all your variables are already in "inputData", so yours,
// also named inputData, must be referenced explicitly.
const result = JSON.parse(inputData.inputData);
return {result: result, firstProfile: result.profiles[0]};

FineUploader Failing to parse incoming JSON

I'm using play/scala for a webapp and a scala API, currently running simply on two different ports on localhost:9000 and localhost:8080 respectively. I have the basic page from the fine-uploader.com website docs, and a simple test page build in Play. (FWIW, i don't think much of the above is relevant)
When i post a file, chunked or not, Fine uploader receives a 200 from the API and valid JSON, but JSON.parse returns a failure. The logging from fine-uploader is below. If i take this output and run it through (in the console)
JSON.parse(JSON.stringify(json))
a valid object is returned. I can't just JSON.parse(json) directly in the browser tools b/c its already an object. I have checked the types by console.log'ing typeOf json in the qq.parseJson method and it returns string, so no conversion should be required, though i have tried it with the same results.
fine-uploader console logs:
[Fine Uploader 5.5.1] Sending simple upload request for 0 fine-uploader.js:251
[Fine Uploader 5.5.1] xhr - server response received for 0 fine-uploader.js:251
[Fine Uploader 5.5.1] responseText = {"code":"UPLOAD_COMPLETE","response":{"MediaModel":{"id":1103,"publicUri":"http://localhost:8080/media/Archive.zip","fileLocation":"/src/services/api/src/main/webapp/media/Archive.zip","mediaDate":{"year":2016,"month":2,"day":28},"mediaOrder":1,"viewName":"","caption":"","altText":"","isPublic":1,"fileSize":1107080,"created":"2016-02-28T14:58:43Z"},"UserMediaModel":{"id":1,"userId":24,"mediaId":3,"created":"2016-02-17T12:48:18Z"}},"errors":[]} fine-uploader.js:251
[Fine Uploader 5.5.1] Received response status 200 with body: {"code":"UPLOAD_COMPLETE","response":{"MediaModel":{"id":1103,"publicUri":"http://localhost:8080/media/Archive.zip","fileLocation":"/src/services/api/src/main/webapp/media/Archive.zip","mediaDate":{"year":2016,"month":2,"day":28},"mediaOrder":1,"viewName":"","caption":"","altText":"","isPublic":1,"fileSize":1107080,"created":"2016-02-28T14:58:43Z"},"UserMediaModel":{"id":1,"userId":24,"mediaId":3,"created":"2016-02-17T12:48:18Z"}},"errors":[]} fine-uploader.js:251
[Fine Uploader 5.5.1] Simple upload request failed for 0
The server is responding with a 200 per the API logs and i can see the exact response object in the Response tab of Chrome Dev tools.
I added a custom error handler, but not more more information was provided, just that the error is the text output
Error on file number 0 - Archive.zip. Reason: {"code":"UPLOAD_COMPLETE",....same as above
Lastly, all rows are propery inserted into the database as you see from the id's created above. And all logging points to an equally successful action.
Thanks for any pointers. I've also put this output in http://jsonlint.com/ and it parses fine.
Thanks! (sorry for the lack of JSON formatting, i can change it, but this seemed long enough already)
EDIT
It seems that i have satisfied the requirements stated in the other question with "success":true and Content-Type=text/plain. The following, per request is the JSON output and the headers
Headers:
Key: Access-Control-Allow-Origin Value: http://localhost:9000
Key: Date Value: Mon, 29 Feb 2016 00:55:19 GMT
Key: Access-Control-Allow-Credentials Value: true
Key: Content-Type Value: text/plain; charset=UTF-8
{
"code": "UPLOAD_COMPLETE",
"response": {
"MediaModel": {
"id": 1169,
"publicUri": "http://localhost:8080/media/Archive.zip",
"fileLocation": "/src/services/api/src/main/webapp/media/Archive.zip",
"mediaDate": {
"year": 2016,
"month": 2,
"day": 28
},
"mediaOrder": 1,
"viewName": "",
"caption": "",
"altText": "",
"isPublic": 1,
"fileSize": 1107080,
"created": "2016-02-29T00:55:19Z"
},
"UserMediaModel": {
"id": 1,
"userId": 24,
"mediaId": 3,
"created": "2016-02-17T12:48:18Z"
}
},
"errors": [],
"success": true
}
I'm sure this will end up being something silly, so i appreciate the input.
Based on the error reported by Fine Uploader, your response is not properly formatted. If you look closely at the response in your browser's network tab (such as with Chrome dev tools), you'll likely see a JSON string that, once parsed using JSON.parse results in another JSON string instead of a JavaScript object containing the expected properties. I can't confirm this as you haven't posted the exact response from your server, but I'm certain that this is the case. This is most likely caused by an encoding issue server-side. For example, your server should return this: {"foo": "bar", "success": true} instead of this: "{\"foo\": \"bar\", \"success\": true}". I suspect your server is returning the latter.

Rally JSON I/O error creating a test case result

I am trying to create a test case result using a REST client, but get this error:
"Errors": ["Cannot parse input stream due to I/O error as JSON document: Parse error: expected '{' but saw '\uFFFF' [ chars read = >>>\uFFFF<<< ]"]
I get the same error when the name of the object, testcaseresult is not specified in the request body. Here are the steps to create a test case result using a browser REST client:
a) Generate the authorize key using "GET" method and the following URL:
https://rally1.rallydev.com/slm/webservice/v2.0/security/authorize
This is the response that I get back, with the security token: "123abc..."
{"OperationResult": {"_rallyAPIMajor": "2", "_rallyAPIMinor": "0", "Errors": [], "Warnings": [], "SecurityToken": "abc123..."}}
b) Use "POST" method, and the following URL:
https://rally1.rallydev.com/slm/webservice/v2.0/testcaseresult/create?key=abc123...
notice the security token in the end.
c) here is an example of a request body:
{
"testcaseresult":
{
"Build":"1",
"Tester":"/user/777",
"Date":"2010-09-04T19:56:05.000Z",
"TestCase":"/testcase/1111",
"Verdict":"Pass"
}
}
Only the required fields and the fields you want to set need to be referenced. Notice the outer key/value pair
{
"testcaseresult":{}
}
The fields that point to a full object, like "Tester" (points to User object) and "TestCase" (points to a TestCase object that owns the result) have to be referenced by their ObjectIDs:
"Tester":"/user/777",
"TestCase":"/testcase/1111",