Frequently, cypress encounters difficulty accessing the /auth page and struggles to locate the necessary id or class

When trying to navigate to the /auth path and log in with Cypress, I am using the following code:

Cypress.Commands.add('login', (email, password) => {
  cy.get('.auth').find('.login').should(($login) => {
    expect($login).to.contain('auth.welcome')
  })

  cy.get('[name="email"]').type(email);
  cy.get('[name="password"]').type(password);

  cy.get('button.login')
    .click();
})

Despite this, Cypress throws an error message:

AssertionError: Timed out retrying: Expected to find element: `.auth`, but never found it.

The code works intermittently.

The URL for my login page is either http://localhost:3000/ or http://localhost:3000/auth

Answer №1

Make sure to include this code snippet before interacting with the element:

cy.get('.auth').should('be.visible');

This command will ensure that the element is visible before proceeding.

Answer №2

Utilizing custom commands can be a valuable tool, but packing multiple UI actions within them can result in slower and less reliable test executions, especially when it comes to login functions.

While your current approach is valid, I would recommend utilizing API calls instead for a more stable and robust login function.

To implement this, you can add a custom command in Cypress like so:
Cypress.Commands.add('login', (username, password) => {
    return cy
        .request('POST', `${<YOUR_API_URL>}/auth`, {
            username,
            password,
        })
        .its('body.token')
        .then(token => {
            cy.visit(`/`, {
                onBeforeLoad(win) {
                    win.sessionStorage.setItem('token', token);
                },
            });
        });
});

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

Dragging objects on a map is done using jQuery and it causes them to bounce

Currently, I am working on implementing the JQuery Draggable feature. My idea is to create a map where I can attach image Divs to it dynamically using Jquery. So far, I have been successful in adding the Divs and making them draggable around the map effici ...

When using window.open in Chrome on a dual screen setup, the browser will bring the new window back to the

When using the API window.open to open a new window with a specified left position in a dual screen setup (screen1 and screen2), Chrome behaves differently than IE and FF. In Chrome, if the invoking screen is on the right monitor, the left position always ...

Working with AngularJS: binding data to dynamically appended HTML elements using JavaScript

Is there a way to connect an angular event and model to an html element that is added through javascript code? To see my code, click here: https://jsfiddle.net/hq7qk48n/13/ <div ng-app> <div ng-controller="MyController"> <input ...

Clicking on a dynamically generated link will not result in the file being downloaded

I have a list of document names and IDs retrieved from a database, displayed in an unordered list like this: <ul id="list"> <li onmouseover="onHover(docNumber)"> <a herf="#" id="docNumber">DocName</a> </li> </ ...

Arranging a list based on the child property in a React component

Within my application, I have an array mapped to a map that generates a div with a data-date attribute as shown below: It's worth noting that the array cannot be sorted here since there are no dates available for comparison, only the element ID cons ...

Google Extension PHP Plugin

Is it feasible to integrate a PHP file into a Google Extension for Chrome? I've been exploring the idea of creating an extension and most resources only mention HTML, CSS, and JavaScript. Any guidance on using PHP in the extension would be highly valu ...

I'm facing an issue where the data I retrieved is not displaying properly in my template within nuxt 3

After fetching data from an api, I can see it logged in my async function. However, the data stored in my array is not rendering on my template in Nuxt 3 The script setup includes: //ARRAY OF ALL THE DAILY WEATHER DATA PER DAY let allDataWeather=[]; ( ...

Ruby on Rails allows for the selection of values in a dropdown menu to trigger the visibility of different sections of HTML

As a newcomer to Rails, I was able to successfully implement the onclick function for a f.checkbox element. Now, my challenge lies in achieving a similar functionality for a f.select element within a _form. Below is the code snippet that works for a chec ...

Tips on customizing the appearance of two Material-UI Sliders across separate components

Looking to customize two sliders, each within their own react component. Slider in the first component const customizedThemeSlider1 = createTheme({ overrides:{ MuiSlider: { thumb:{ color: "#4442a9", marg ...

Acquire the content of an interactive website with Python without using the onclick event

I am looking to extract the content of a dynamically generated website after clicking on a specific link. The link is structured as follows: <a onclick="function(); return false" href="#">Link</a> This setup prevents me from directly accessin ...

The auto-refresh feature of DataTables is not functioning as expected

Having trouble with the reload feature of DataTables. This is the code I'm using to load and reload the table on the server-side: $( document ).ready(function() { $('#dienst_tabelle').DataTable( { "ajax": "getData ...

Is there a way to execute a Node 6 npm package within a Node 5.6.0 environment?

I am currently utilizing a tool called easy-sauce to conduct cross-browser JavaScript tests. Essentially, my package.json file references this tool for the test command: { "scripts": { "test": "easy-sauce" } } Everything runs smoothly when I exec ...

The act of exporting an enum from a user-defined TypeScript path leads to the error message "Module not

I have set up a custom path as explained in this particular discussion. "baseUrl": ".", "paths": { "@library/*": [ "./src/myFolder/*" ], } Within this module, I am exporting an Enum. export enum EN ...

I would like the capability to choose a roster of gods depending on a character's class and moral orientation

I am in the process of developing a character sheet for Dungeons & Dragons, and I'm looking to pass the values from two drop-down menus into a query that will then populate another select list. Despite trying various methods to retrieve the data, I ke ...

The files being requested by jQuery Slimbox are not being retrieved properly

I am currently utilizing jQuery slimbox along with its Application Programming Interface (API). Below is the JavaScript code snippet that retrieves image paths through JSON and then triggers the slimbox using its API. $('#main-container').appen ...

How to manually trigger the ajaxLoader feature in Tabulator version 3.5

Currently, I am working with version 3.5 of Tabulator from . When populating the table using an ajax request, a "loading icon" is displayed during the loading process. Prior to executing the ajax request for Tabulator, I perform some preliminary check op ...

What is the best method for typing a component prop that is compatible with singular use and can also function within loops without disrupting intellisense?

The Scenario Within a heading component, I have defined various types as shown below: // Heading/index.d.ts import { HTMLAttributes } from 'react'; export const HeadingType: { product: 'product'; marketing: 'marketing'; ...

Problem with nesting lists in VueDraggable

I am looking to incorporate the VueDraggable library into my project in order to create nested lists. I followed the documentation to create a component, and everything is working well except for one issue: I am unable to create new nested items. The onl ...

The declaration file for the module 'bootstrap/dist/js/bootstrap' could not be located

Currently, I am developing a Next.js application and have integrated Bootstrap for styling. However, I am encountering an error when trying to import the bootstrap.bundle.js file. I am facing the following error message: Could not find a declaration file f ...

Send the input's value to v-model

Is there a way to automatically pass the value of the input into the v-model? Thank you :) Here is the code snippet: <input value="{{$in->id}}" v-model="upload.id"> I attempted the following in my script: upload: { bank:'', ...