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

Steps for toggling between enabling and disabling the 2 instances of bvalidator

Running on my form are two instances of bvalidator found at . The first instance validates the entire form, while the second instance only partially validates the same form. In total, the form contains 2 buttons: The first button saves form data upon va ...

Rearranging div placement based on the width of the screen

I am currently working on building a responsive website and I need two divs to switch positions depending on the screen width, both on initial load and when resizing. Despite my efforts in researching and trying various options, I have not been successful ...

Switching between all tabs simultaneously in an MDX page (React + Gatsby + MDX) using @reach/tabs

Creating a Tab component for a Gatsby site has proved to be a bit tricky. Imagine having a page with multiple tabs all labeled the same: Heading 1 First tab block Tab 1 | Tab 2 Content Tab 1 Second tab block Tab 1 | Tab 2 Content Tab 1 for the second bl ...

Guide to displaying a component within the Vue instance

I am currently in the process of developing a Nuxt module that will not interfere with the main Nuxt application. My approach involves creating a separate Vue instance and mounting it as a child node under the body element, similar to a child node to the _ ...

What is the process for removing an added message using jQuery after it has been appended by clicking the same button?

https://i.stack.imgur.com/YsmKZ.pnghttps://i.stack.imgur.com/dW2lo.pngI have searched extensively through previously asked questions without success. My goal is to remove the previous appended message when the submit button is clicked again. This functiona ...

What is the best way to send the value from a textbox to this script?

My challenge is with this particular textbox: <input type="text" autocomplete="off" required="required" id="bar" name="bar" class="form-control" placeholder="Barcode"> Also, there's a button in the mix: <button type="button" style="float:r ...

Multiple ngFor loops causing only the final item to be displayed in the inner loop

Can someone assist with my code where I loop through firebase RTDB reference to retrieve a list and then use those results in a subsequent firestore query? The console logs the correct data, but my code only displays the last item in the loop inside ngFor. ...

Encountering a ReferrenceError when utilizing jQuery with TypeScript

After transitioning from using JavaScript to TypeScript, I found myself reluctant to abandon jQuery. In my search for guidance on how to integrate the two, I came across several informative websites. Working with Visual Studio 2012, here is my initial atte ...

Find a way to incorporate social media features into a web application that functions intermittently

Currently, I am in the process of developing a social media app and working on integrating a search feature to enable users to find friends. The code I have below seems to be functional at times but not consistent (quite frustrating!) The issue seems to st ...

Formik state is mysteriously reverting field values to their default state

I've encountered an issue with my form and song state while trying to add a new field called "appleMusicId". Unfortunately, every time I add this field, it seems to reset the values of timeDescription and sceneDescription. I've spent hours tryin ...

Is there a way to disable automatic spacing in VS code for a React file?

I am currently working on my code in VS Code within my JSX file, but I keep encountering an error. The issue seems to be that the closing tag < /h1> is not being recognized. I have attempted multiple methods to prevent this automatic spacing, but so ...

Guide on implementing router-link within a select option dropdown in a Vue.js application

a.vue <template> <div>hi i am component 1</div> </template> <script> export default { name: "a", }; </script> b.vue <template> <div>hi i am component 2</div> </template> <script> ...

problems encountered when including next.config.js for sitemap creation in a nextjs application

Just recently, I made an update to my next.config.json file in hopes of boosting SEO performance. However, this change has caused some issues with the next-sitemap module, preventing me from building or starting my app. //next.config.js const withSitemap = ...

Click on the print icon in the modal window

I have been working on a receipt generator for a client. The client can add payment receipts using the "Add" button, and upon submission, they have the option to convert it to PDF or print it. However, there seems to be an issue with printing as the text f ...

Discover the steps to retrieve a fresh array in PHP after utilizing sortable.js

Hi there! I am currently utilizing the sortable javascript feature found on Although the script is working perfectly fine for me, being a non-expert in javascript poses a challenge when it comes to generating the necessary code to retrieve an array in php ...

Incorporate 'Additional features' into the Navbar when adjusting window size

When the window is resized, I want to display a collapsed 'More options' button that will collapse all hidden <li> elements. Here is an example: <li id="menu_more_container" class="dropdown" style="display: none; ...

Maintain the newly selected background color for the current day in fullcalendar when navigating to the next or previous month

Currently, I am working on a project in React using npm fullcalendar. One of the requirements is to change the color of the current day. After some trial and error, I was able to achieve this by adding the following code: $('.fc-today').attr(&ap ...

Looking to screen usernames that allow for the use of the DOT (.), underscore (_), and Dash (-)?

I am using jQuery to filter usernames that are exactly 3 characters long. The validation criteria includes only allowing the following special characters: ., _, and - var filter = /^[a-zA-Z0-9]+$/; Therefore: if (filter.test(currentval)) { //valid ...

Despite changes in the state they are set to, the InitialValues remain constant

I am facing an issue with a Semantic-UI modal that includes a redux-form as its content. The form is passed to the modal when it opens, and the form element has an initialValues prop mapped to state. <FormModal handl ...

Error: Unable to retrieve the specified ID

One unique aspect of my backbonejs app is the model structure: var Store = Backbone.Model.extend({ urlRoot: "/stores/" + this.id }); This is complemented by a router setup like so: var StoreRouter = Backbone.Router.extend({ routes: { 's ...