Skip to content

Instantly share code, notes, and snippets.

@fityanos
Created May 25, 2022 05:55
Show Gist options
  • Save fityanos/738763191b23f937aa48ec422c31abc6 to your computer and use it in GitHub Desktop.
Save fityanos/738763191b23f937aa48ec422c31abc6 to your computer and use it in GitHub Desktop.

Testing and validating the redirection/URL of a QR Code is essential for a Test Engineer as you don't want to lose a chance of downloading your business App or even worse redirect to broken/wrong one

How to achieve this:

1- You need to install some dependencies which include a module that have API to decode QR Code/Barcode and read it for Cypress.io

npm i @zxing/browser
npm i @zxing/library

2- Create HTML image element under a Cypress Command in support/commands.js

const imgReader = new BrowserMultiFormatReader(); // new module from the dependincy

/**
 * Cypress custom command that you will create
 */
Cypress.Commands.add("readQRCode", { prevSubject: true }, (imgUnderTest) => {
  const businessImg = imgUnderTest[0]; // store the yielded imgUnderTest subject in const called bsuinessImg
  
  const htmlImg = new Image(); // create new HTML image element <img>
  
  htmlImg.width = businessImg.width; // assign the QRCode image width to the newly created HTML image element
  
  htmlImg.height = businessImg.height; // assign the QRCode image height to the newly created HTML image element
  
  htmlImg.src = businessImg.src; // assign the QRCode image src to the newly created HTML image element
  
  htmlImg.crossOrigin = "Anonymous"; // assign cross origin to the newly created HTML image element

  return imgReader.decodeFromImageElement(htmlImg); // returns in a Promise the image properties that i can use to assert my test
});

Important Note(s) we passed the option prevSubject: true to yield the previous command subject. (This will help us in the spec.js file)

3- Now, we need to write our test file spec.js

describe("I need to validate my QR Code", () => {

  it("should validate QR Code URL", () => {
    cy.visit("/"); // visit your app
    
    cy.get("QRCode_selector") // get the QR Code selector
    
      .readQRCode() // run your custome command ( prevSubject is beneficial here to yield true the cy.get command)
      
      .should("have.property", "text", "your_text"); // run assertions....
  });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment