Read JSON data in Testcafe

To perform Data-driven automation in Testcafe, we have to use some external resources to store the data, It can be a JSON, Excel, or a text file. but the best way is to store the data into a JSON file. In this Testcafe example, we will see how to create end-to-end data-driven automation tests in Testcafe using JSON.

The basic testcafe configuration will be required to run these examples, so if it’s not done at your machine yet, check out the Testcafe configuration tutorial

Read JSON data in Testcafe

Creare an external JSON file data.json. That contains some requirement data or you can say configuration things. Like URL, Wait time, and user name and password. that we will use during the automation.

data.json

{

    "url":"codebun.com",
    "shortWait": 1000,
    "mediumWait": 5000,
    "timeout": 5000,
    "longWait": 10000,
    "users": {
        "username":"Testing@gmail.com",
        "password":"Test@123"
    }
}

Create a Testcase file “test.js” that contains a testcase, Where we will read the URL and Username and print on the console from the data.json file

test.js

import { Selector } from 'testcafe';
import config from '../data.json';


fixture `Read data from JSON file` 
//.page `https://codebun.com/`

 test.only('Read URL and User name from data.json', async t => {

      //Read and Print URL from data.json file
      console.log(config.url)
      //Read Username from data.json file
      console.log(config.users.username)
      
  });

import config from '../data.json'; is used to import the JSON file from the existing path. Now we have a config object to read any value or data from the respective JSON file.

Output