What is the reason for Cypress choosing to omit specific commands?

The test below aims to scan and authenticate a QR code, then utilize the received authentication token. However, for some reason, the last two commands (.type) are not being executed. I've been stuck at this point for quite some time now. Any insights on why this might be happening?

getUrlVars is a helper function that returns the string used to generate the token.

Thank you.


        /// <reference types='Cypress' />
    import { Decoder } from "@nuintun/qrcode";
    const qrcode = new Decoder();
    const OTPAuth = require("otpauth");
    
    import Navbar from "../page-objects/components/Navbar";
    import UserProfileNav from "../page-objects/components/UserProfileNav";
    import BasePage from "../page-objects/pages/BasePage";
    import LoginPage from "../page-objects/pages/LoginPage";
    import RegistrationPage from "../page-objects/pages/RegistrationPage";
    import { createEmail, getUrlVars } from "../utils/utils";
    
    describe("test", () => {
      it("ttest", () => {
        cy.visit("/");
        LoginPage.login("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1d5c4d2d5fe909791999093939393959799978fcacad7c3d7d7cad2e1ccc0c8cdced2c0d4d38fc8ce">[email protected]</a>", "P@ssword1");
        Navbar.navigateToProfile();
        UserProfileNav.twoStepVerificationTab();
    
        cy.findAllByAltText("2FA QR kód").then(function ($img) {
          qrcode.scan($img.prop("src")).then((result) => {
            const totp = new OTPAuth.TOTP({
              algorithm: "SHA1",
              digits: 6,
              period: 30,
              secret: getUrlVars(result.data)["secret"],
            });
            const token = totp.generate();
            console.log(token);
            cy.findByLabelText("Jednorázový kód").type(token);
          });
        });
      });
    });

Answer №1

Have you attempted this approach? It's possible that the issue is related to the asynchronous nature of javascript, where this section runs first:

const token = totp.generate();
console.log(token);
cy.findByLabelText("Jednorázový kód").type(token);

which is followed by:

const totp = new OTPAuth.TOTP({
  algorithm: "SHA1",
  digits: 6,
  period: 30,
  secret: getUrlVars(result.data)["secret"],
});

This leads to an error where the token is undefined. To address this, we need to utilize then() to instruct Cypress to execute everything synchronously.

/// <reference types='Cypress' />
import {
  Decoder
} from "@nuintun/qrcode";
const qrcode = new Decoder();
const OTPAuth = require("otpauth");

import Navbar from "../page-objects/components/Navbar";
import UserProfileNav from "../page-objects/components/UserProfileNav";
import BasePage from "../page-objects/pages/BasePage";
import LoginPage from "../page-objects/pages/LoginPage";
import RegistrationPage from "../page-objects/pages/RegistrationPage";
import {
  createEmail,
  getUrlVars
} from "../utils/utils";

describe("test", () => {
  it("ttest", () => {
    cy.visit("/");
    LoginPage.login("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b0f1e080f244a4d4b434b494949474d45454943060751454b59484c4c4b564585">[email protected]</a>", "P@ssword1");
    Navbar.navigateToProfile();
    UserProfileNav.twoStepVerificationTab();

    cy.findAllByAltText("2FA QR kód").then(function($img) {
      qrcode.scan($img.prop("src")).then((result) => {
        const totp = new OTPAuth.TOTP({
          algorithm: "SHA1",
          digits: 6,
          period: 30,
          secret: getUrlVars(result.data)["secret"],
        }).then((totp) => {
          const token = totp.generate();
          console.log(token);
          cy.findByLabelText("Jednorázový kód").type(token);
        });
      });
    });
  });
});

Answer №2

Thank you to everyone who offered their assistance - this solution resolved my issue.

     cy.findAllByAltText("2FA QR code").then(async function ($img) {
            await qrcode.scan($img.prop("src")).then((result) => {
              const totp = new OTPAuth.TOTP({
                algorithm: "SHA1",
                digits: 6,
                period: 30,
                secret: getUrlVars(result.data)["secret"],
              });
              token = totp.generate();
            });
    
            cy.findByLabelText("One-time code").type(token);
            cy.findByRole("button", { name: "Save" }).click({
              force: true,
            });
            cy.findByText("Device has been successfully configured.").should("be.visible");
          });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering an HTML Element in a JavaScript Array with Specific Styling: A Step-by-Step Guide

I am in the process of developing a website that consists of different sections. The concept is simple - by clicking on a button located at the bottom of the page, it will reveal the corresponding div section. For styling purposes, I have initially hidden ...

Is there an issue with the proper execution of keypresses/updates in the code

I'm currently stuck while trying to develop a game in Javascript. My challenge lies in detecting keypresses and constantly checking if they are being held down to move the character. Below is the code I have been using: var THREE; var keys; var updat ...

The Impact of Ajax on Online Search Algorithms

There's a website that dynamically loads content at . An example page from the site can be found at: . The entire content on this page is generated using a cURL parser script. <?php $___notjson=1; ini_set('display_errors', 1); header (&a ...

Navigating Users After Form Validation in React - A Step-By-Step Guide

As a newcomer to React, I am currently working on a SignUp SignIn project. My goal is to route the user to the Login/SignIn page upon successful form validation. Below is my SignUp code: import React, { Component } from 'react'; import { Link } f ...

Button's focus event doesn't trigger on iPad

I am facing an issue with adding a bootstrap popover to my website. The popover should appear when the user clicks a button using the focus event. This functionality works fine on desktop browsers, but on the iPad, it seems like Safari on iOS does not trig ...

Trouble concealing tab using slideUp function in Jquery

Whenever I click on the 'a' tag, it displays additional HTML content (list) that is controlled by generic JS code for tabs. However, I want to hide the list when I click on the "Title" link again. What can I do to achieve this? You can view a de ...

What is the process for adding color to an Object3D Object in ThreeJs?

My project involves importing Objects from a file, and I want to be able to color them by clicking on them. After attempting the following code: let mat = (this.scene.children[4].getObjectByName(intersects[0].object.name) as THREE.Mesh).material.color.set ...

Merge the chosen values from the drop-down menu into one string

Any suggestions would be greatly appreciated! I am currently developing an application using ASP.NET web forms that consists of a dropdown list and two list boxes. I want these elements to be cloned whenever a specific button is clicked. However, my issue ...

Warning: Unhandled Promise Rejection - Alert: Unhandled Promise Rejection Detected - Attention: Deprecation Notice

Encountering the following error message: (node:18420) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'name' of undefined at C:\Users\ohrid\Desktop\backend2\routes\categories.js:27:24 at Layer.han ...

The debate between centralization and specification: the ultimate Javascript/jQuery best practice for web applications

Picture a scenario where a web application consists of numerous page groups (pg1, pg2, ...) and some of these page groups require specific JavaScript code that is only relevant to them, not the entire app. For instance, certain visual adjustments on window ...

Choosing various li classes within a navigation bar

Struggling to pick the right JQuery elements for my portfolio site. The aim is to show/hide the .inner (Task) items by clicking on the .outer (Category) items, complete with rotating .arrows when the menu expands. Check out a similar question, along with ...

The Angular directive alters the scope, however, the template continues to display the unchanged value

I am working with a directive that looks like this: .directive('myDirective', function() { return { restrict: 'AE', replace: true, templateUrl: '/myDirective.html?v=' + window.buildNumber, ...

Using React refs to target multiple elements dynamically with the help of the map

My code effectively catches when the dropdown is clicked outside, and it's working well: displayOptions() { return _.map(this.props.selections, (option, index) => { return ( <div className="ui icon top dropdown" ...

Exploring ways to incorporate mouse movements into this simple JavaScript script

I have recently decided to convert my JavaScript code into jQuery code to incorporate mouse events. After downloading the latest version of jQuery and renaming it as "jquery.js," I made modifications to my manifest.json file by adding "jquery.js." However, ...

Error not identified in ajax function for form submission

For some reason, in IE8 specifically, the alert function is not firing and the ajax part of my code is not running when I try to submit a form. Even though I have included a return false, the form still gets submitted. Why is this issue only occurring in ...

Maintain the same javascript variable throughout multiple pages

I am working on a project that involves utilizing a database along with 2 drop down menus. Through the use of JavaScript, I am able to capture the value selected from the drop down menus and then pass it on to my PHP script. The PHP script retrieves releva ...

Hold on for the completion of Angular's DOM update

I am facing an issue where I need to connect the bootstrap datepicker to an input field generated by AngularJS. The typical approach of using jQuery to attach the datepicker doesn't work as expected because the element is not yet available: $(functi ...

Issue with React and Material UI: The Textfield's "onChange" event is not being triggered

I have been attempting to trigger an onchange function when my Textfield is populated, but for some reason the function never seems to be activated. Despite seeing changes triggered by the React devtool plugin in Chrome, I am at a loss. Any suggestions? i ...

Is there a way to deactivate a JavaScript function on a specific webpage using CSS?

I've implemented a JavaScript function that triggers a pop-up alert whenever a user attempts to navigate away from the site by clicking on an external link: $("a[target='_blank']").click( function() { return confirm('Please don&apo ...

Mongoose Alert Utility Directive

const mongoose = require('mongoose'); module.exports = { init: () => { const dbOptions = { useNewUrlParser: true, useUnifiedTopology: true, autoIndex: false, reconnectTries: Number.MA ...