Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

cypress-crud

Package Overview
Dependencies
Maintainers
0
Versions
271
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cypress-crud

cy.crud is a project that aims to have a new framework to make cy.api and cy.request easier

  • 2.5.0
  • Source
  • npm
  • Socket score

Version published
Maintainers
0
Created
Source

Cypress-Crud Introduction

Index

  • Prerequisites
  • Installation
  • Configuration

Structure of the files

Type of Functions

Support


Pre-requisitos

NodeJS must be installed and Cypress must be version 10 or higher for this package to function correctly.

 NodeJs
 Cypress version 10 >

Installation

To install the package in your Cypress project, use the command

npm i cypress

npx cypress open

and

configure cypress

npm i cypress-crud

Configuration

The CRUD was designed to automatically add dependencies and configurations to the e2e.js file and the cypress.config.js file, eliminating the need to manually include anything for the library's functionality.

  • e2e.js:
export {
  crudStorage,
} from "cypress-crud/src/gherkin/bdd.js";
import "cypress-plugin-steps";
export const faker = require("generate-datafaker");
import "cypress-crud";
import "cypress-plugin-api";
import "cypress-mochawesome-reporter/register";
import spok from "cy-spok";
// export default spok;
const applyStyles = require("../../node_modules/cypress-crud/src/style");
if (!Cypress.env("styles") && Cypress.env("crudStyles")) applyStyles();
// close json file in variable
import _ from "lodash";
export function clone(json) {
  return _.cloneDeep(json);
}
  • cypress.config.js:

const { defineConfig } = require("cypress");

module.exports = defineConfig({
  reporter: "cypress-mochawesome-reporter",

  e2e: {
    setupNodeEvents(on, config) {
      require("cypress-mochawesome-reporter/plugin")(on);
      on("task", {
        crudLog(message) {
          console.log(message);
          return null;
        },
      });
      // adjust to print size
      on("before:browser:launch", (browser, launchOptions) => {
        if (browser.family === "chromium" && browser.name !== "electron") {
          launchOptions.args.push("--window-size=1500,1200");
        }
        if (browser.name === "electron") {
          launchOptions.preferences.width = 1500;
          launchOptions.preferences.height = 1200;
        }
        if (browser.family === "firefox") {
          launchOptions.args.push("--width=1500");
          launchOptions.args.push("--height=1200");
        }
        return launchOptions;
      });
    },
    testIsolation: false, //  in e2e:{}
    experimentalRunAllSpecs: true, // in e2e:{}
  },
});
  • cypress.env.json:
{
  "environment": "QA",
  "QA": {
    "endpoint": "https://restcountries.com/v3.1/translation/germany",
    "reqres": "https://reqres.in/api/users/2",
    "swagger": "https://fakerestapi.azurewebsites.net/api/v1/",
    "location": "https://rickandmortyapi.com/api/location"
  },
  "PROD": {
    "endpoint": "https://restcountries.com/v3.1/translation/germany",
    "reqres": "https://reqres.in/api/users/2",
    "swagger": "https://fakerestapi.azurewebsites.net/api/v1/",
    "location": "https://rickandmortyapi.com/api/location"
  },
  "DEV": {
    "endpoint": "https://restcountries.com/v3.1/translation/germany",
    "reqres": "https://reqres.in/api/users/2",
    "swagger": "https://fakerestapi.azurewebsites.net/api/v1/",
    "location": "https://rickandmortyapi.com/api/location"
  },

  "screenshot": false, // active for screenshot un mod run
  "crudStyles": true
  // "title": "TESTING",
  // "subTitle": "Project in Cypress"
}
  • commands.js:
// CREATE COUNTER IMPORT IN FILE .CY.JS

IMPORT IN FILE  // import { des, its } from "../support/commands";

const counter = window;
let compare;
if (!counter.des) {
  counter.des = 1;
  counter.its = 1;
}
const confer = () => counter.des;
console.log(confer());

export let des = () => {
  return String(counter.des++).padStart(2, "0") + " ➠ "  ;
};
export let its = () => {
  if (!compare || confer() !== compare) {
    counter.its = 1;
    compare = confer();
  }
  return String(counter.its++).padStart(2, "0") + " - " ;
};
  • env_qa.js:
const { defineConfig } = require("cypress");

const config = require("./cypress.config");

const e2e = {
  ...config.e2e,
  env: {
    endpoint: "https://restcountries.com/v3.1/translation/germany",
    reqres: "https://reqres.in/api/users/2",
    swagger: "https://fakerestapi.azurewebsites.net/api/v1/",
    location: "https://rickandmortyapi.com/api/location",
    ...config.env,
  },

  testIsolation: false, //  in e2e:{}
  experimentalRunAllSpecs: true, // in e2e:{}
  chromeWebSecurity: false,
};

module.exports = defineConfig({
  ...config,
  e2e,
});

// IN PACKAGE.JSON
// "scripts": {
//     "cy:run:qa": "cypress run --config-file env_qa.js"
//   },
  • package.json
// create new environment DEV env_dev.js, env_prod.js
"scripts": {
    "cy:run:qa": "cypress run --config-file env_qa.js",
    "cy:open:qa": "cypress open --config-file env_qa.js",

  }
  • interface

  • cypress-plugin-api: default

Demonstração do recurso

JSON Fixtures:

  • Version 2.4.4 +

Use faker. options for generate data faker


    {
      "post": "swagger/login",
      "body": {
        "username": "admin",
        "password": "password",
        "name": "faker.name", // faker.nome
        "email": "faker.email",
        "enterprise": "faker.enterpriseName", // faker.empresaNome
        "state": "faker.state", // faker.estado
        "city": "faker.city", // faker.cidade
        "country": "faker.country", //faker.pais
        "street": "faker.street", // faker.endereco // faker.address // faker.rua
        "phoneNumber": "faker.phoneNumber", // faker.numeroTelefone
        "cep": "faker.cep",
        "cpf": "faker.cpf",
        "cnpj": "faker.cnpj",
        "passwords": "faker.password", //faker.senha
        "uuid": "faker.uuid",
        "birthdate": "faker.birthdate", // faker.aniversario
        "avatar": "faker.avatar",
        "professional": "faker.professional", // faker.profissao
        "product": "faker.product", // faker.produto
      },
    };


// result

    {
      "username": "admin",
      "password": "password",
      "test": "Jam Batista",
      "email": "joaogabriel@hotmail.com",
      "enterprise": "Ana Clara CloudNet",
      "state": "Ceará",
      "city": "Guatemala City",
      "country": "Alemanha",
      "street": "Alhambra, Granada, Spain",
      "phoneNumber": "11995655467",
      "cep": "69304525",
      "cpf": "94344989023",
      "cnpj": "02708629000116",
      "passwords": "4)={[W.oHj",
      "uuid": "0de2e006-8bfa-44cb-b05f-d3c019249a20",
      "birthdate": "1952-06-15T02:41:02.520Z",
      "avatar": "https://avatars.githubusercontent.com/u/36132952"
    }

  • Version 2.4.1 +

it("Run all JSONs in folder", () => {
  cy.runFixtures("examples"); // run all JSONs in folder
});
it("Run all JSONs", () => {
  cy.runFixtures(); // run all JSONs in fixtures
});
  • Version 2.4.0 +

{
  "post": "swagger/login-hard", // get delete put path
  "body": {
    "username": "admin",
    "password": "password"
  },
  "status": 201,
  "expect": "token"
}
{
  "method": "GET", // or get: true // post: true // delete": true // path: true
  "url": "getUser"
}

File test: Pass afterEach

    afterEach(() => {
    cy.crudScreenshot();
  });

Guide to building the project

For your project setup, you need to create a JSON file inside the Fixtures folder. This file can be placed directly in the folder or within a subfolder for better organization according to your project's needs.

Example path: Fixtures/Token/createToken.json

{
  "method": "GET", // or get: true // post: true // delete": true // path: true
  "url": "https://reqres.in/api/users/2",
  "body": null,
  "qs": null,
  "headers": {
    "Content-Type": "application/json"
  }
}

Or in your test file

let obj = {
  method: "GET",
  // or get: true // post: true // delete": true    url: "https://reqres.in/api/users/2",
  body: null,
  qs: null,
  headers: {
    "Content-Type": "application/json",
  },
};

Once your JSON file is set up, you can simply invoke the cy.crud function in your test file to make the request.

Observation: If your JSON file is located in the 'fixtures' folder, simply specify the path including the name of the subfolder and the JSON file to access it.

cy.crud({ payload: "examples/jsonExamples" });

Observation: If your JSON file is outside the 'fixtures' folder, it is necessary to use the import statement.

import json from "../examples/jsonExamples";

cy.crud({ payload: json });

Snippets

A snippet has been created to streamline the test construction process.

  • crud
cy.crud({ payload: "" });
  • .save
.save({path:''})
  • .bodyResponse
.bodyResponse({path:''})
  • .resp
.response({path:''})
  • .expects
.expects({path:''})
  • .schema
.schema({schema:''})

```

Nested json, with the url like this ``` the code will look for the endpoint or any name given in the
env:{ endpoint: "http....." } and concatenate with /users

// get_AllUsers.json get_idUser.json ...
{
  "url": "endpoint/users"
}

cy.crud

The cy.crud function facilitates making requests with a specific payload and assessing the response.

Example:

     cy.crud({ payload: "examples/jsonEndpoint" });

save

The 'save' method reserves // or get: true // post: true // delete": true a value inserted to be used in the future when requested.

Example:

cy.crud({ payload: "token/createToken.json" }).save({ path: "name" });

console.log("storage", crudStorage.save.name);

explanation: Saves the value 'name' in crudStorage

Another way to use save is by passing aliases, providing an alternative name for a stored value, simplifying its reference and usage in your test code.

cy.crud({ payload: "token/createToken.json" }).save({ path: "name", alias: "user_name" });

console.log('storage', crudStorage.save.user_name)

bodyResponse

The bodyResponse function is used to check if the response body contains a specific value at a given path.

cy.crud({ payload: "token/createToken.json" }).bodyResponse({path: "name", eq:"Jam Batista"})

response

The response function performs the same task as the bodyResponse function, i.e., it checks if the response body contains a specific value at a given path.

cy.crud({ payload: "token/createToken.json" }).response({path: "name", eq:"Jam Batista"})

expects

The expects function performs the same task as the previous functions, i.e., it checks if the response body contains a specific value at a given path.

cy.crud({ payload: "token/createToken.json" }).expects({path: "name", eq:"Jam Batista"})

schema

The schema function performs the same task as the validateSchema command. It ensures that the response of a request adheres to the criteria specified in a particular JSON schema. This validation helps confirm whether the returned structure and data align with the expectations defined in the test.

 cy.crud({ payload: "examples/jsonNotAlias" }).schema({schema: "jsonSchema",});

res

The res function serves the same purpose as the response command. It validates if the response body contains a specific value at a given path. This validation is crucial for ensuring that the response meets the expected criteria defined in the test.

  cy.crud({ payload: put }).res({ path: 'job' }, { path: 'name' })

validateSchema

The validateSchema command is used to ensure that the response of a request meets the criteria defined in a specific JSON schema. This is useful for verifying if the returned structure and data are correct according to the test expectations.

  cy.crud({ payload: "examples/jsonNotAlias" }).validateSchema({schema: "jsonSchema",});

write

This function is used to write data to a JSON file in the Cypress fixtures directory. It creates a JSON file with the provided data from the specified request response. This is useful for generating simulated response files for testing purposes.

cy.crud({ payload: "token/createToken.json" }).write({ path: "user/getUser" });

explanation: create json response in cypress/fixtures/user


read

This function is used to read data from a JSON file in the Cypress fixtures directory. It reads the content of the specified JSON file and makes it available for use in the test

cy.crud({ payload: "token/createToken.json" }).read({ path: "user/getUser" });

cy.read({ path: "user/getUser" }).then((json) => {
  console.log(json);
});

explanation: read json response in cypress/fixtures/user


Type Validations

There are two ways to perform validations: within the test file and within the JSON file. Both are designed to facilitate the construction process.

  • JSON Validation fixtures: After creating the JSON, you can use either the 'validation' or 'expects' key:
{

    "method": "GET", // or get: true // post: true // delete": true
    "url": "https://reqres.in/api/users/2",
    "body": null,
    "qs": null,
    "headers": {
      "Content-Type": "application/json"
    }

  "validation": [{ "path": "status", "eq": 200 }, { "path": "first_name" }, ...],

  //Or To validate just one field

  "validation":{ "path": "status", "eq": 200 },

  // Or validate the field with two values

  "validation":{ "path": "name", "eq": "Jam || Batista" }

}

OR

{

    "method": "GET", // or get: true // post: true // delete": true
    "url": "https://reqres.in/api/users/2",
    "body": null,
    "qs": null,
    "headers": {
      "Content-Type": "application/json"
    }

  "expects": [{ "path": "status", "eq": 200 }, { "path": "first_name" }, ...],

  //Or To validate just one field

  "expects":{ "path": "status", "eq": 200 },

  // Or validate the field with two values

  "expects":{ "path": "name", "eq": "Jam || Batista" }
}

OR

{

    "method": "GET", // or get: true // post: true // delete": true
    "url": "https://reqres.in/api/users/2",
    "body": null,
    "qs": null,
    "headers": {
      "Content-Type": "application/json"
    }

  "expect": [{ "path": "status", "eq": 200 }, { "path": "first_name" }, ...],

  //Or To validate just one field

  "expect":{ "path": "status", "eq": 200 },

  // Or validate the field with two values

  "expect":{ "path": "name", "eq": "Jam || Batista" },

  // have property in all json

  "expect":{ "property": "name" }
}

OR

{

    "method": "GET", // or get: true // post: true // delete": true
    "url": "https://reqres.in/api/users/2",
    "body": null,
    "qs": null,
    "headers": {
      "Content-Type": "application/json"
    }

  "response": [{ "path": "status", "eq": 200 }, { "path": "first_name" }, ...],

  //Or To validate just one field

  "response":{ "path": "status", "eq": 200 },

  // Or validate the field with two values

  "response":{ "path": "name", "eq": "Jam || Batista" }
}

OR

{
  "req": {
    "method": "GET", // or get: true // post: true // delete": true
    "url": "https://reqres.in/api/users/2",
    "body": null,
    "qs": null,
    "headers": {
      "Content-Type": "application/json"
    }
  },
  "res": [{ "path": "status", "eq": 200 }, { "path": "first_name" }, ...],

  //Or To validate just one field

  "res":{ "path": "status", "eq": 200 },

  // Or validate the field with two values

  "res":{ "path": "name", "eq": "Jam || Batista" }
}

OR

{

    "method": "GET", // or get: true // post: true // delete": true
    "url": "https://reqres.in/api/users/2",
    "headers": {
      "Content-Type": "application/json"
    }

  "checks": [{ "path": "status", "eq": 200 }, { "path": "first_name" }, ...],

  //Or To validate just one field

  "checks":{ "path": "status", "eq": 200 },

  // Or validate the field with two values

  "checks":{ "path": "name", "eq": "Jam || Batista" }
}

OR

{

    "method": "GET", // or get: true // post: true // delete": true
    "url": "https://reqres.in/api/users/2",
    "headers": {
      "Content-Type": "application/json"
    }

  "check": [{ "path": "status", "eq": 200 }, { "path": "first_name" }, ...],

  //Or To validate just one field

  "check":{ "path": "status", "eq": 200 },

  // Or validate the field with two values

  "check":{ "path": "name", "eq": "Jam || Batista" }
}

OR

{

    "method": "GET", // or get: true // post: true // delete": true
    "url": "https://reqres.in/api/users/2",
    "headers": {
      "Content-Type": "application/json"
    },
  "check": [{ "path": "status", "eq": 200 }, { "path": "first_name" }, ...],

  //Or To validate just one field

  "check":{ "path": "status", "eq": 200 },

  // Or validate the field with two values

  "check":{ "path": "name", "eq": "Jam || Batista" }
}

Schema Validator

Create schema in path fixtures

{

    "method": "GET",
    "url": "https://reqres.in/api/users/2",
    "headers": {
      "Content-Type": "application/json"
    },
    "schema": "schemas/token",
  "check": [{ "path": "status", "eq": 200 }, { "path": "first_name" }, ...],

  //Or To validate just one field

  "check":{ "path": "status", "eq": 200 },

  // Or validate the field with two values

  "check":{ "path": "name", "eq": "Jam || Batista" }
}

  • Test Validation: The bodyResponse, response, res, and expects functions are responsible for this:

cy.crud({ payload: "token/createToken.json" }).bodyResponse({path: "name", eq:"Jam Batista"})
cy.crud({ payload: "token/createToken.json" }).response({path: "name", eq:"Jam Batista"})
cy.crud({ payload: "token/createToken.json" }).expects({path: "name", eq:"Jam Batista"})
cy.crud({ payload: "token/createToken.json" }).res({ path: "job" }, { path: "nam" })


  • Validation type - file Test: You can use this option to validate the nature of the field, whether it's an Object, a Number, a String, etc.

cy.crud({ payload: "token/createToken.json" }).bodyResponse({path: "name", type:"string"})
cy.crud({ payload: "token/createToken.json" }).response({path: "value", eq: 1, type: "number"})
cy.crud({ payload: "token/createToken.json" }).expects({path: "enterprise", type: "object"})
cy.crud({ payload: "token/createToken.json" }).res({ path: "users", type: "array" })

OR

  • Validation type - JSON fixtures: You can use this option to validate the nature of the field, whether it's an Object, a Number, a String, etc.
{

    "method": "GET", // or get: true // post: true // delete": true // path: true
    "url": "https://reqres.in/api/users/2",
    "body": null,
    "qs": null,
    "headers": {
      "Content-Type": "application/json"
    }

  "validation": [{ "path": "name", "type": "string" }],
  // OR

  "expects": [{ "path": "value", "eq": 1, "type": "number" }],

  // OR

  "expect": [{ "path": "value", "eq": 1, "type": "number" }],

  // OR

  "response": [{ "path": "enterprise", "type": "object" }],

  // OR

  "res": [{ "path": "users", "type": "array" }],

  // OR

  "checks": [{ "path": "name", "type": "string" }],

  // OR

  "check": [{ "path": "value", "eq": 1, "type": "number" }]
}

Another validation method introduced is the search for specific values, this way saves this value automatically, but to save it with a specific value, just pass the alias, or as.

{

    "method": "GET", // or get: true // post: true // delete": true // path: true
    "url": "https://reqres.in/api/users",
    "headers": {
      "Content-Type": "application/json"
    }

  "validation": [{ "search": "Jam" }, { "search": 200, "alias": "value" }],
  //OR
  "expects": [{ "search": "Jam" }, { "search": 200, "as": "status_code" }],
  //OR
  "expect": [{ "search": "Jam" }, { "search": 200 }],
  //OR
  "response": [{ "search": "Jam" }, { "search": 200 }],
  //OR
  "res": [{ "search": "Jam" }, { "search": 200 }],
  //OR
  "checks": [{ "search": "Jam" }, { "search": 200 }],
  //OR
  "check": [{ "search": "Jam" }, { "search": 200 }]
}

Type save

The save is used to Store the provided value so that it can be retrieved and used later as required.

  • File Test: The value located at the path specified by the path parameter, in this case, "access_token", is retrieved and assigned the name "bearer_token" via the alias. This procedure ensures that the "access_token" value can be accessed and used later in the code under the name "bearer_token".
cy.crud({ payload: "token/createToken.json" }).save({ path: "access_token", alias: "bearer_token"}) // OR as: "bearer_token"});
  • JSON fixtures: The value located in the path defined by the save parameter, here being "access_token".
{
  "method": "GET", // or get: true // post: true // delete": true // path: true
  "url": "https://reqres.in/api/users",
  "body": null,
  "qs": null,
  "headers": {
    "Content-Type": "application/json"
  },
  "save": { "path": "access_token" },
  "save": { "path": "access_token", "as": "token" }
}
  • Search option: By using the search command to locate the desired field, you can choose to save it with a specific value by employing the term 'alias'.

JSON fixtures:

Inside the JSON file located in the fixtures

{

    "method": "GET", // or get: true // post: true // delete": true // path: true
    "url": "https://reqres.in/api/users",
    "headers": {
      "Content-Type": "application/json"
    }

  "validation": [{ "search": "access_token", "alias": "bearer_token" }], // OR as: "bearer_token" }],
  //OR
  "expects": [{ "search": "access_token", "alias": "bearer_token" }],
  //OR
  "expect": [{ "search": "access_token", "alias": "bearer_token" }],
  //OR
  "response": [{ "search": "access_token", "alias": "bearer_token" }],
  //OR
  "res": [{ "search": "access_token", "alias": "bearer_token" }],
  //OR
  "checks": [{ "search": "access_token", "alias": "bearer_token" }],
  //OR
  "check": [{ "search": "access_token", "alias": "bearer_token" }]
}

File Test

creating variable

let payload = {

    method: "GET", // or get: true // post: true // delete": true // path: true
    url: "https://reqres.in/api/users",
    headers: {
      "Content-Type": "application/json"
    }


  validation: [{search: "access_token", alias: "bearer_token"}],
  //OR
  expects: [{search: "access_token", alias: "bearer_token"}],
  //OR
  expect: [{search: "access_token", alias: "bearer_token"}],
  //OR
  response: [{search: "access_token", alias: "bearer_token"}],
  //OR
  res: [{search: "access_token", alias: "bearer_token"}],
  //OR
  checks: [{search: "access_token", alias: "bearer_token"}],
  //OR
  check: [{search: "access_token", alias: "bearer_token"}]
}

validation method

cy.crud({payload: "examples/jsonExamples"}).bodyResponse({search: "access_token", alias: "bearer_token"})

// OR

cy.crud({payload: "examples/jsonExamples"}).response({search: "access_token", alias: "bearer_token"})

// OR

cy.crud({payload: "examples/jsonExamples"}).expects({search: "access_token", alias: "bearer_token"})

//OR

cy.crud({payload: "examples/jsonExamples"}).res({search: "access_token", alias: "bearer_token"})

Managing values with Save

To reuse the values ​​stored in other requests, simply reference the path in the JSON file within the fixtures, using the value associated with the alias. If an alias was not specified, the values ​​can be accessed directly using whatever is passed in path or search.

Example 1°: In the previous example, we used the search and path parameters to locate the access_token value, which was then stored under the name bearer_token using the alias parameter. In the following example, we will demonstrate how this stored value is utilized in the Authorization. Furthermore, we use replace to adapt and apply the value to other variables, enabling flexible manipulation of this data in different contexts of the request.

{
  "method": "POST", // or get: true // post: true // delete": true // path: true
  "url": "https://reqres.in/api/users",
  "headers": {
    "Content-Type": "application/json",
    "Authorization": "Bearer {bearer_token}"
  }
}

Example 2°: For scenarios such as appending a value to the URL being passed, simply include the path variable and the value assigned to alias or use the value specified in search and path.

{
  "method": "POST", // or get: true // post: true // delete": true // path: true
  "url": "https://reqres.in/api/users",
  "path": "bearer_token",
  "headers": {
    "Content-Type": "application/json"
  }
}

Alternatively, in situations where it is necessary to concatenate the stored value with another value to be passed simultaneously, you can simply use / for concatenation. In the following example, the value is stored in the id key, but the request also requires the city to complete. To achieve this, the city is concatenated with the id value stored in the path, as shown below:

{
  "method": "POST", // or get: true // post: true // delete": true // path: true
  "url": "https://reqres.in/api/users",
  "path": "id/city",
  "headers": {
    "Content-Type": "application/json"
  }
}

//exit example -> https://reqres.in/api/users/123456789/city

Example 3°: For situations requiring validation of the value stored in the alias or specified in the search and path, In the example below, a value has been stored under the key user, eliminating the need to pass the value itself—only the key is required.

{

    "method": "POST", // or get: true // post: true // delete": true // path: true
    "url": "https://reqres.in/api/users",
    "headers": {
      "Content-Type": "application/json"
    }

  "validation": [{ "path": "name_user", "eq": "{user}" }],
  //OR
  "expects": [{ "path": "name_user", "eq": "{user}" }],
  //OR
  "expect": [{ "path": "name_user", "eq": "{user}" }],
  //OR
  "response": [{ "path": "name_user", "eq": "{user}" }],
  //OR
  "res": [{ "path": "name_user", "eq": "{user}" }],
  //OR
  "checks": [{ "path": "name_user", "eq": "{user}" }],
  //OR
  "check": [{ "path": "name_user", "eq": "{user}" }]
}


Use Mock

For requests that require a mock, simply specify the mock variable and provide the path to where the mock is stored.

Example: The file can be found in fixtures in the mocks folder, called json_mock.

{
  "method": "GET", // or get: true // post: true // delete": true // path: true
  "url": "https://demo0065046.mockable.io/",
  "mock": "mocks/json_mock",
  "headers": {
    "Content-Type": "application/json"
  }
}

Mock construction:

{
  "response": {
    "status": 200,
    "body": { "authorization": "Bearer" }
  }
}

In this example, the body field directs to the mock file located in the mocks folder, which contains the predefined structure of the fields to be returned in the response.

Validate mock: To validate the mock, you can simply include the checks in the JSON file itself or embed them in the test file.

  • JSON fixtures
{
  "method": "GET", // or get: true // post: true // delete": true // path: true
  "url": "https://demo0065046.mockable.io/",
  "mock": "mocks/json_mock",
  "headers": {
    "Content-Type": "application/json"
  }
}

  • Tips

cy.crud({ url: "swagger/eventos", expect: "id::id" }); // save id expect:{path: "id", as: "id"}
cy.crud({ url: "swagger/eventos", expect: "name===Jam" }); // equal result expect:{path: "name", eq: "Jam"}


crudSafeData

describe(`Test cypress-crud Property search`, () => {
  let data;
  const token =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJrZXkiOiIxMjM0NTY3ODkwIiwicGFzc3dvcmQiOiJKb2huIERvZSJ9.d7gibg6eK9oxrpcCob-MuNz65NHMWNK1x4otVLyHPCo";

  before(function () {
    cy.crudSafeData(token).then((safe) => {
      crudStorage.save.email_login = safe.key;
      crudStorage.save.password_login = safe.password;
    });
  });

  it("Decode", () => {
    console.log(crudStorage.save);
  });
});

  OUR

  IN CYPRESS.ENV.JSON

  "dataSafe": "token jwt",
  "hideCredentials": true,
  "hideCredentialsOptions": { "body": ["email", "password"] } // change for your paths

  COMPLETE ENV
    env: {
        hideCredentials: true,
        hideCredentialsOptions: {
          headers: ['authorization'],
          auth: ['pass'],
          body: ['username'],
          query: ['password']
        }
      }

   OUR

  CYPRESS.CONFIG.JS

  env:{
  "dataSafe": "token jwt",
  "hideCredentials": true,
  "hideCredentialsOptions": { "body": ["email", "password"] } // change for your paths
  }

  COMPLETE ENV
    env: {
        hideCredentials: true,
        hideCredentialsOptions: {
          headers: ['authorization'],
          auth: ['pass'],
          body: ['username'],
          query: ['password']
        }
      }

hideReport

// in cypress.env.json

 "hideReport": ["body", "headers"]

 // result

 {
  "method": "POST",// or get: true // post: true // delete": true // path: true
  "url": "https://reqres.in/api/users/2",
  "failOnStatusCode": false,
  "body": "hide active in path",
  "headers": "hide active in path"
}


  • Report

To generate the report, the tests must be executed in run mode. Furthermore, to include screenshots of the request payload in the report, a specific configuration needs to be adjusted in the cypress.config.js file and in your test file.

cypress.config.js: To activate the option, simply add screenshot: true

{
  "environment": "QA",
  "QA": {
    "endpoint": "https://restcountries.com/v3.1/translation/germany",
    "reqres": "https://reqres.in/api/users/2",
    "swagger": "https://fakerestapi.azurewebsites.net/api/v1/",
    "location": "https://rickandmortyapi.com/api/location",
    "swagger": "https://tranquil-cove-07655-38b519d38c2f.herokuapp.com/"
  },
  "PROD": {
    "endpoint": "https://restcountries.com/v3.1/translation/germany",
    "reqres": "https://reqres.in/api/users/2",
    "swagger": "https://fakerestapi.azurewebsites.net/api/v1/",
    "location": "https://rickandmortyapi.com/api/location",
    "swagger": "https://tranquil-cove-07655-38b519d38c2f.herokuapp.com/"
  },
  "DEV": {
    "endpoint": "https://restcountries.com/v3.1/translation/germany",
    "reqres": "https://reqres.in/api/users/2",
    "swagger": "https://fakerestapi.azurewebsites.net/api/v1/",
    "location": "https://rickandmortyapi.com/api/location",
    "swagger": "https://tranquil-cove-07655-38b519d38c2f.herokuapp.com/"
  },

  "screenshot": false, // active for screenshot un mod run
  "crudStyles": true
  // "title": "TESTING",
  // "subTitle": "Project in Cypress"
}

Authors and Contributors

This project is the collaborative effort of Jameson Batista and Gabriel Lopes. We are proud to share our work with the community and hope it can inspire and assist other developers.

For tips, inquiries, or just to connect, follow us on LinkedIn:

Keywords

FAQs

Package last updated on 25 Jun 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc