Testcafe how to read json response and pick first item and pass it to selector

Viewed 1085

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

2 Answers

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.

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']
}
Related