How to Validate JSON Schema in REST Assured?

Here are the steps:

Step 1: Transform JSON to JSON Schema, using tool https://transform.tools/json-to-json-schema

JSON

{
    "name": "morpheus",
    "job": "leader"
}

JSON Schema

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Generated schema for Root",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "job": {
      "type": "string"
    }
  },
  "required": [
    "name",
    "job"
  ]
}

Step 2: Paste JSON schema to .json file inside src/test/resources. I have pasted it to schema/reqres/createuser.json

Step 3: Add JSON Schema validator dependency

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>5.4.0</version>
</dependency>

 Step 4: Import matcher

import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;

Step 5: Call Matcher in response body

@Test
public void JSONSchemaValidator()
{
    RestAssured.baseURI = "https://reqres.in/";
    RestAssured.basePath = "/api/";
					
    User userObj = new User("Ram", "QA");
					
    given()	
        .header("Content-Type","application/json")
            .body(userObj)
        .when()
            .post("/users")
        .then()
            .body(matchesJsonSchemaInClasspath("schema/reqres/createuser.json"));			
}

How to Create Patch Request Using REST Assured?

Code

@Test
public void reqResPatchRequest() 
{
    RestAssured.baseURI = "https://reqres.in/";
    RestAssured.basePath = "/api/";
		
    Response res = 
        given()
            .header("Content-type", "application/json")
            .pathParam("userID", "3")
            .body("{\n"
                + "    \"name\": \"morpheus\",\n"
                + "    \"job\": \"zion resident\"\n"
                + "}")
        .when()	
            .patch("/users/{userID}")
        .then()
            .statusCode(200)
            .extract().response();
            
        res.body().prettyPrint();
	}

How to Create Post Request Using REST Assured?

Code:

@Test
public void ReqResPostRequest()
{
    RestAssured.baseURI = "https://reqres.in/";
    RestAssured.basePath = "/api/";
		
    Response res = given()	
        .header("Content-Type","application/json")
        .body("{\n"
            + "    \"name\": \"morpheus\",\n"
            + "    \"job\": \"leader\"\n"
            + "}")
        .when()
            .post("/users")
        .then()
            .statusCode(201)
            .extract().response();
		
        // Print response body
        res.body().prettyPrint();
}

How to Send GET Request in REST Assured?

Code

public void ReqRestGetRequest() 
{
    RestAssured.baseURI = "https://reqres.in/";
    RestAssured.basePath = "/api/";
		
    given()
        .queryParam("page","2")
    .when()
        .get("/users/")
    .then()
        .statusCode(200);
}

How to Use Map in JavaScript?

A Map holds key-value pairs where the keys can be any datatype. A Map remembers the original insertion order of the keys. A Map has a property that represents the size of the map.

Here are the methods:

  1. new Map(): Creates a new Map object
  2. set(): Sets the value for a key in a Map
  3. get(): Gets the value for a key in a Map
  4. clear(): Removes all the elements from a Map
  5. delete(): Removes a Map element specified by a key
  6. has(): Returns true if a key exists in a Map
  7. forEach(): Invokes a callback for each key/value pair in a Map
  8. entries(): Returns an iterator object with the [key, value] pairs in a Map
  9. keys(): Returns an iterator object with the keys in a Map
  10. values(): Returns an iterator object of the values in a Map

To create map, use

const fruits = new Map([
  ["apples", 100],
  ["bananas", 70],
  ["oranges", 50]
]);

console.log(fruits)

or

// Create a Map
const fruits = new Map();

// Set Map Values
fruits.set("apples", 100);
fruits.set("bananas", 70);
fruits.set("oranges", 50);

console.log(fruits)

What are the Advantages of JavaScript?

JavaScript offers numerous advantages for web development and beyond:

  1. Client-Side Interactivity: JavaScript is primarily a client-side scripting language, allowing dynamic and interactive elements within web pages. It enables the creation of responsive and engaging user interfaces.
  2. Versatility: It's a versatile language used for a wide range of tasks, from front-end web development (DOM manipulation, animations, form validation) to back-end development (Node.js).
  3. Ease of Learning: JavaScript is relatively easy to learn and use, especially for those familiar with HTML and CSS. Its syntax is similar to many other programming languages, making it accessible for beginners.
  4. Wide Adoption and Support: It's one of the most widely adopted programming languages with a vast community of developers. This leads to extensive documentation, libraries (like React, Vue.js, etc.), and support available online.
  5. Cross-Browser Compatibility: Modern browsers support JavaScript, making it a reliable choice for web development. Additionally, JavaScript frameworks often provide abstractions that handle cross-browser inconsistencies.
  6. Asynchronous Programming: JavaScript supports asynchronous programming paradigms through features like callbacks, Promises, and async/await, enabling the creation of non-blocking code and efficient handling of operations.
  7. Enhanced User Experience: With JavaScript, developers can create rich, interactive experiences for users, including animations, real-time updates, form validations, and more, leading to a more engaging user experience.
  8. Server-Side Development: With the introduction of Node.js, JavaScript can now be used for server-side development. It allows developers to use the same language for both client-side and server-side scripting, leading to more seamless application development.
  9. Community and Ecosystem: JavaScript has a vast ecosystem with numerous libraries, frameworks, and tools that aid in development, testing, debugging, and deployment.
  10. Constant Evolution: JavaScript constantly evolves with new features and updates (ECMAScript versions) aimed at improving the language's capabilities, performance, and security.

These advantages contribute to the widespread use and popularity of JavaScript in web development and its expanding role in other areas like mobile app development (using frameworks like React Native and Ionic) and even in IoT (Internet of Things) applications.

What is a Closure in JavaScript?

Closures are an ability of a function to remember the variables and functions that are declared in its outer scope.

Code

function myFunction()
{
    var obj1 = {name:"Ram", age:35};
    
    return function()
    {
        console.log(obj1.name + ", "+ "How are you!"); 
        // Has access to obj1 even when the myFunction is executed
    }
}

var initialiseClosure = myFunction(); // Returns a function

initialiseClosure(); 

What is Scope Chain in JavaScript?

If the javascript engine does not find the variable in local scope, it tries to check for the variable in the outer scope. If the variable does not exist in the outer scope, it tries to find the variable in the global scope.

If the variable is not found in the global space as well, a reference error is thrown.

var y = 20;

function fun1()
{
  var x = 10;
  var fun2 = function()
  {
    console.log(x); // Output 10
  }

  var fun3 = function(){
    console.log(y); // output 20
  }

  fun2();
  fun3();
}

fun1();

What are the Advantages of using External JavaScript?

Using external JavaScript files offers several benefits:

  1. Separation of Concerns: It helps separate the HTML content from JavaScript logic, making code more organized, readable, and maintainable. This separation enhances code reusability and makes it easier to manage.
  2. Caching: External JavaScript files can be cached by browsers. When a user visits a site that uses external JavaScript, after the initial download, subsequent visits or page loads can use the cached file, reducing load times and server requests, thus improving performance.
  3. Faster Page Load: Placing JavaScript code in an external file allows the browser to load the HTML content first, enhancing the initial page load speed. This is because the browser can load other resources (like images, stylesheets, etc.) concurrently while fetching the JavaScript file.
  4. Maintenance and Updates: Making changes or updates to JavaScript functionality becomes easier when it's in an external file. Modifications can be applied to a single file that's linked across multiple web pages, avoiding the need to edit each individual HTML file.
  5. Improved Code Reusability: External JavaScript files can be reused across multiple web pages within the same site or even across different websites, promoting modular and reusable code practices.
  6. Cleaner HTML Markup: Keeping JavaScript in external files reduces the clutter within the HTML file, resulting in cleaner and more understandable markup.
  7. Accessibility: External JavaScript files can be accessed and utilized by multiple pages on a website, improving accessibility to functions and methods throughout the site.

However, it's essential to ensure proper referencing and management of these external files. Overuse or improper handling of external JavaScript files might lead to increased HTTP requests or potential issues if the linked files are deleted or moved without updating the references.

What is Currying in JavaScript?

Currying is an advanced technique to transform a function of arguments n, to n functions of one or fewer arguments. For Example, if we have a function f(a,b), then the function after currying, will be transformed to f(a)(b). By using the currying technique, we do not change the functionality of a function, we just change the way it is invoked.

Code

function sum(a, b)
{
    return a + b;
}

function currying(fn)
{
    return function(a)
    {
        return function(b)
        {
            return fn(a, b);
        }
    }
}

var curriedSum = currying(sum);

console.log(sum(2, 3)); // Returns 5
console.log(curriedSum(2)(3)); // Also returns 5
teststep banner