Json File stores the keys value pair in a file separated by a :(colon), we can read JSON files in JSON files in Protractor without using any extra package
JSON is an acronym and translated into JavaScript Object Notation. Its inventor is famously quoted for having said, "It doesn’t take a rocket scientist to create a better (relational) file format for JavaScript than XML.
Which implies its purposes. He’s right (Douglas Crockford); unfortunately, it (also) doesn’t take a rocket scientist to create a better (relational) file format than JSON too. I should now because I’ve arguably done the latter myself.
#JSON file
{
"cat": {
"legs": 4,
"colour": "brown"
}
}
JSON's primary usage is for transmitting data, often from a server to a client, to facilitate AJAX. AJAX is what facilitates a rich experience on the web, allowing for incrementally apply changes to a website, using data from the server.
The format is widely accepted everywhere as it is a lightweight alternative of XML, XML is difficult to read, JSON much easier. Also, JSON takes less storage compared to XML.
JSON Parser is inbuilt in most browsers, and JSON is also a widely accepted data exchange format against XML web services for the same.
Due to its ease of use and the relative popularity of JavaScript frameworks, the JSON is being used in rest APIs, and whenever the JavaScript code in the browser communicates with the server.
Copy the below content into a file and save the file with .json format, For example : cherchertech.json
#cherchertech.json file
{
"name": "karthiq",
"age": 27,
"gender": "Male",
"website": "cherchertech protractor"
}
To read the JSON data from the file, we can use the fs module present in the Node.js. fs module manipulates the files present in the system like reading, write, and update.
There are two functions available in this module that we can use to read files from the file system:
The readFileSync function reads data from a file in a synchronous manner. readFileSync function blocks the rest of the code from executing until all the data is read from a file.
The function is particularly useful when your application has to load configuration settings before it can perform any other task.
The below code will help you to read the total JSON file, and also print it to the console.
// import the fs module
const fs = require('fs');
// read the file into raw data
let rawdata = fs.readFileSync('cherchertech.json');
// parse the raw data into meaningful JSON format
let author = JSON.parse(rawdata);
console.log(author);
In the above code, we have read the total Json file and printed it to the console, but when it comes to real life, we would not just stop with reading the file, we have to use the individual value for some purpose.
Let's say use the above code snippet into out protractor program and search in google using the "website" value present in the JSON file.
describe('Protractor Typescript Demo', function() {
browser.ignoreSynchronization = true; // for non-angular websites
it('Javascript executions', function() {
// import the fs module
const fs = require('fs');
// read the file into raw data
let rawdata = fs.readFileSync('D:Protractor Democherchertech.json');
// parse the raw data into meaningful JSON format
let web = JSON.parse(rawdata);
web["website"]let websiteValue = web["website"]
q and set the value using the sendKeys methodRead a value from a JSON file using Protractor
import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
import { Alert, WebElement } from 'selenium-webdriver';
describe('Protractor Typescript Demo', function() {
browser.ignoreSynchronization = true; // for non-angular websites
it('Json File Reading', function() {
// set implicit time to 30 seconds
browser.manage().timeouts().implicitlyWait(30000);
// navigate to the url
browser.get("https://google.com");
// import the fs module
const fs = require('fs');
// read the file into raw data
let rawdata = fs.readFileSync('D:Protractor Democherchertech.json');
// parse the raw data into meaningful JSON format
let web = JSON.parse(rawdata);
let websiteValue = web["website"]
console.log("Website value from Json file is : " +websiteValue)
element(by.name("q")).sendKeys(websiteValue);
});
});
Another way you can read a JSON file in NodeJS is by using the readFile function. Unlike readFileSync function, the readFile function reads file data in an asynchronous manner.
When a readFile function is called, the file reading process starts, and immediately, the control shifts to the next line executing the remaining lines of code.
Once the file data has been loaded, this function will call the callback function provided to it. This way, you aren't blocking code execution while waiting for the operating system to get back to you with data.
The below example showcases, how to use the readFile() method in protractor.
import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
import { Alert, WebElement } from 'selenium-webdriver';
describe('Protractor Typescript Demo', function() {
browser.ignoreSynchronization = true; // for non-angular websites
it('Javascript executions', function() {
// set implicit time to 30 seconds
browser.manage().timeouts().implicitlyWait(30000);
// navigate to the url
browser.get("https://google.com");
// import the fs module
const fs = require('fs');
// read the file into raw data
let rawdata = fs.readFile("D:Protractor Democherchertech.json", 'utf8', function(err, contents) {
// parse the raw data into meaningful JSON format
let web = JSON.parse(contents);
let websiteValue = web["website"]
console.log("Website value from Json file is : " +websiteValue)
// see below for the note
browser.sleep(5000)
element(by.name("q")).sendKeys(websiteValue);
});
});
});
rawdata() method gets executed before even trying to execute any other command in the code.
Normally we use require for importing the node modules, and packages but we can use it for loading the JSON file in protractor.
With this method, we do not have to use the wait statement, and it is not an asynchronous method to read. I prefer this method for reading the JSON file along with the protractor.
import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
import { Alert, WebElement } from 'selenium-webdriver';
describe('Protractor Typescript Demo', function() {
browser.ignoreSynchronization = true; // for non-angular websites
it('Javascript executions', function() {
// set implicit time to 30 seconds
browser.manage().timeouts().implicitlyWait(30000);
// navigate to the url
browser.get("https://google.com");
// load the Json file
const totalContent = require('D:Protractor Democherchertech.json');
let websiteValue = totalContent["website"]
console.log("Website value from Json file is : " +websiteValue)
element(by.name("q")).sendKeys(websiteValue);
});
});
Rules for using require along with JSON in protractor:
The actual truth is you may not be working with simple JSON files like above; most of the time, JSON files will have nested values like the below file.
We may save our test data in JSON files in protractor; as JSON files are platform-independent, so JSON files are a good option for storing test data in protractor.
Save the content of below in some files with JSON extension.
{
"author":{
"name": "karthiq",
"age": 27,
"gender": "Male",
"website": {
"name": "chercher tech",
"tagline": "Learning is Fun",
"topics": "Future technologies"
}
}
}
From the above files, let's read the tagline value present inside the "website" value; the website values are present inside the "author value.
For reading nested values, we may need to group the values similar to a map, In the below example, we will be searching the "tagline" value in google.
const fs = require('fs');
readFileSync() from the fs module in javascript// read the file into raw data
let rawdata = fs.readFileSync('D:Protractor Democherchertech.json');
let author = web["author"]
browser.sleep(1).then(function(){
console.log("
###### Author value ########
")
console.log(author)
})
let website = author["website"]
browser.sleep(1).then(function(){
console.log("
****** Website value ******
")
console.log(website)
})
let taglineBySteps = website["tagline"]
browser.sleep(1).then(function(){
console.log("
@@@@@@ tagline value @@@@@
")
console.log(taglineBySteps)
})
[key] to the value we havelet taglineDirect = web["author"]["website"]["tagline"]
browser.sleep(1).then(function(){
console.log("
^^^^^^^ tagline value Direct^^^^^^
")
console.log(taglineDirect)
})
Complete program for reading nested JSON file in Protractor with Typescript
import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
import { Alert, WebElement } from 'selenium-webdriver';
describe('Protractor Typescript Demo', function() {
const fs = require('fs');
let sampleMap = new Map();
browser.ignoreSynchronization = true; // for non-angular websites
it('Javascript executions', function() {
// set implicit time to 30 seconds
browser.manage().timeouts().implicitlyWait(30000);
// navigate to the url
browser.get("https://google.com");
const fs = require('fs');
// read the file into raw data
let rawdata = fs.readFileSync('D:Protractor Democherchertech.json');
// parse the raw data into meaningful JSON format
let web = JSON.parse(rawdata);
let author = web["author"]
browser.sleep(1).then(function(){
console.log("
###### Author value ########
")
console.log(author)
})
let website = author["website"]
browser.sleep(1).then(function(){
console.log("
****** Website value ******
")
console.log(website)
})
let taglineBySteps = website["tagline"]
browser.sleep(1).then(function(){
console.log("
@@@@@@ tagline value @@@@@
")
console.log(taglineBySteps)
})
let taglineDirect = web["author"]["website"]["tagline"]
browser.sleep(1).then(function(){
console.log("
^^^^^^^ tagline value Direct^^^^^^
")
console.log(taglineDirect)
})
element(by.name("q")).sendKeys(taglineBySteps);
});
});
The output of the reading nested JSON values program
[11:13:05] I/local - Selenium standalone server started at http://172.19.113.1:54633/wd/hub
Started
###### Author value ########
{ name: 'karthiq',
age: 27,
gender: 'Male',
website:
{ name: 'chercher tech',
tagline: 'Learning is Fun',
topics: 'Future technologies' } }
****** Website value ******
{ name: 'chercher tech',
tagline: 'Learning is Fun',
topics: 'Future technologies' }
@@@@@@ tagline value @@@@@
Learning is Fun
^^^^^^^ tagline value Direct^^^^^^
Learning is Fun
.
1 spec, 0 failures
Finished in 2.695 seconds
Check whether Webpage loaded or not in Javascript in Protractor.
Sometimes we may need to write the files as well, similar to the readFile and readFileSync functions; there are two functions for writing data to files:
The writeFile method writes data to a file in an asynchronous way while writeFileSync function writes data to a file in a synchronous manner.
const fs = require('fs');
let site = {
name: 'cherchertech',
previousName: "selenium-webdriver.com"
};
let data = JSON.stringify(site);
fs.writeFileSync('site-details.json', data);
In the above topic, we have seen how to write predefined values into protractor, but when it comes to the protractor, we may need to fetch values from the web page and store it into a JSON file.
In the below example, We will be fetching the title and font-size attribute from the google search bar into a JSON file.
I would recommend reading how to get font-size(CSS value) and title attribute in protractor
import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
import { Alert, WebElement } from 'selenium-webdriver';
describe('Protractor Typescript Demo', function() {
const fs = require('fs');
browser.ignoreSynchronization = true; // for non-angular websites
it('Javascript executions', function() {
// set implicit time to 30 seconds
browser.manage().timeouts().implicitlyWait(30000);
// navigate to the url
browser.get("https://google.com");
// get attribute
element(by.name("q")).getAttribute("title").then(function(toolTip){
// get css value
element(by.name("q")).getCssValue("font-size").then(function(font_size){
let googleBar = {
title: toolTip,
fontSize: font_size
};
let data = JSON.stringify(googleBar);
fs.writeFileSync('searchbarDetails.json', data);
})
})
});
});
In the above output, you can see that the JSON file is stored in a single line, but it is not so readable to make it more readable pass a few more parameters with JSON.stringfy method
let data = JSON.stringify(sampleMap, null, 3);
Here the parameter 3 is nothing but how many spaces we have to give for each row, I have used this below, converting Typescript Map to JSON file with protractor program.
Most of the time we will store a collection of objects either in List or in Map, we can convert this map into JSON file format, but we cannot convert the list into JSON file format because Map stores the values in key-value pair format similar to JSON files.
import { browser, element, by, ExpectedConditions, protractor} from 'protractor'
import { Alert, WebElement } from 'selenium-webdriver';
describe('Protractor Typescript Demo', function() {
const fs = require('fs');
let sampleMap = new Map();
browser.ignoreSynchronization = true; // for non-angular websites
it('Javascript executions', function() {
// set implicit time to 30 seconds
browser.manage().timeouts().implicitlyWait(30000);
// navigate to the url
browser.get("https://google.com");
// get attribute
element(by.name("q")).getAttribute("title").then(function(toolTip){
// get css value
element(by.name("q")).getCssValue("font-size").then(function(font_size){
sampleMap["title"] = toolTip;
sampleMap["fontSize"] = font_size;
let data = JSON.stringify(sampleMap, null, 3);
fs.writeFileSync('abc.json', data);
})
})
});
});
I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.
please share the information about read/write MHTML file using protractor and also compare two mhtml file
Hi KarthiQ, Could you please send me the offline protractor notes. Thanks in advance, Mahendar
if i had one why whould i refer to this online notes bro