3

Read JSON response

1) When I visit this URL 'http:example.com/fruits', it hits an endpoint 'http:example.com/v1/collections/fruits' and I see JSON in the browser network response:

{
   "total":3,
   "page":1,
   "pageSize":24,
   "rows":[
      {
         "id":19,
         "title":"Apple"

      },
      {
         "id":21,
         "title":"Grape",

      },
      {
         "id":6,
         "title":"Orange",

      },

   ]
}

2) I want to pick up the first title - Apple and pass it to a selector and click on it

3
  • 1
    What exactly do you mean with 'pass it to a selector and click on it'? Commented Jun 12, 2019 at 13:33
  • @Brainfeeder identify the correct selector with the title and then instruct testcafe to click on said selector
    – lostlemon
    Commented Jun 12, 2019 at 14:39
  • Ah yes the answer and the examples in testcafe docs should do for OP then..? Commented Jun 12, 2019 at 15:19

2 Answers 2

5

In your app, you can create 'GET' method, like:

fetch('http:example.com/v1/collections/fruits', {
  method: 'GET'
})
.then(response => response.json())
.then(data => {
  console.log(data.rows[0]['title']) // should return 'Apple'
})
.catch(error => console.error(error))

And after that, you can pass it to your selector.

0

You could also use RequestHook to obtain this information.

This could live in a helper file

import { RequestHook } from 'testcafe';

export default class MyRequestHook extends RequestHook {
    constructor (requestFilterRules, responseEventConfigureOpts,ObjToReturn) {
        super(requestFilterRules, responseEventConfigureOpts);
        this.ObjToReturn = ObjToReturn;
    }
    onRequest (event) {
        if(event.isAjax) {
            console.log(event.requestOptions.url);
        }
    }
    onResponse (event) {
        this.ObjToReturn = JSON.parse(event.body.toString());
    }
}

Then, this would be in your main test file:

import { Selector } from 'testcafe';
import MyRquestHook from './MyHTTPRequestFile';

let getReponse = {};
const hookConfigOptions = {
    logResponseBody: true,
    stringifyResponseBody: true,
    includeHeaders: true,
    includeBody: true
}

let getFruits = new MyRequestHook({url:'http://example.com/fruits', method: 'get'},hookConfigOptions,getResponse);

fixture `Name Of test`
    .requestHooks(getFruits)

test('Do something with response', async t => {
    //do something with the response object
    console.log("Response Data: " + getFruits.rows[0]['title']
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.