Encountering a promise error in Cypress when attempting to send an API request

I encountered a promise error while using cypress; how can I resolve this issue?

let woID = 0
let woCoordinate = 0
let keyCloakToken = 0

class utils {
 createIncidentViaAPI() {

        keyCloakToken = localStorage.getItem('keycloak-token')
        fetch('https://URL', {
            headers: {
                accept: 'application/json, text/plain, */*',
                authorization: 'Bearer ' + keyCloakToken,
                'content-type': 'application/json;charset=UTF-8',
            },
            body: '{"description":"keycloak","type":"SY","startDate":"2022-08-14T12:19:00.000Z","locationAddress":"Japanese Pagoda Ohio Dr SW","latitude":38.88366120709875,"longitude":-77.04149404953358,"sourceType":"CALL"}',
            method: 'POST'
        })
            .then((res) => res.json())
            .then((out) => {
                cy.log(out.data.incidentId)
            })
    }

The fetch request at the top is functioning smoothly without any issues. However, I am facing challenges with the API request at the bottom.

It is crucial to note that when I send the createWorkOrderViaAPI() request, I need to wait for 60-70 seconds as the system responds every 60 seconds. Therefore, I attempted to use the then block. Despite trying different options, I have not been able to solve the promise problem.


     createWorkOrderViaAPI() {
        cy.request({
            url: 'URL',
            method: 'POST',
            headers: {
                properties: 'wonum',    
                'Content-Type': 'application/json',
                MAXAUTH: 'autpassword',
                Authorization: 'Basic ' + 'autpassword'
            },
            body: {
                description: 'test request',
            }
        }).then((res) => {
            woID = res.body.wonum  
// Here, I aim to retrieve some numbers and subsequently use them in the second API request within the then block.
        }).then((out)=>{
            fetch('https://URL', {
                headers: {
                    accept: 'application/json, text/plain, */*',
                    'accept-language': 'tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7',
                    authorization: 'Bearer ' + keyCloakToken,
                    
                },
                body:
                    '{"statusList":"sortDirection":"DESC","archivalTypeList":["ACTIVE"],"countByField":"NEIGHBORHOOD","searchText":"' +
            ---> I intend to use the woID number here ---> woID +
                    '}',
                method: 'POST'
            }).then((res) => {
                woCoordinate = res.body.wkt
                cy.log(woCoordinate)
            })
        })
    }
    

Upon executing this code, I receive an error message from cypress regarding promises. The error message document is provided below:

https://i.sstatic.net/9O1hT.png

You can also refer this link for more information.

Answer №1

The issue arises when attempting to utilize cy. functions within a then block.

.then(()=>{
avoid utilizing any Cypress methods here
}) 

To resolve this, I isolated my custom API calls and eliminated the Cypress requests that were causing conflicts.

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

Exploring bar charts with negative values using Dygraph in R

I have time-series data that I want to visualize in R using dygraphs with bars instead of lines. I found a custom plotter function on the dygraphs documentation and tried implementing it: dyBarChart <- function(dygraph) { dyPlotter(dygraph = dygraph, ...

Error: Unable to access undefined properties (attempting to read 'getBoundingClientRect')

I keep encountering the issue TypeError: Cannot read properties of undefined (reading 'getBoundingClientRect') while working in React on my localhost with Node.js. I can't figure out what's causing it. import React,{useRef,useState} fro ...

Utilize various arrays within a single component

Incorporating react, I am faced with the challenge of passing data by props to a component that originates from two separate arrays. How can I effectively pass this data while ensuring only one component is created? If I attempt to map both arrays as is, ...

Issue: [ng:areq] The argument 'HelloController' is not defined as a function, it is displayed as undefined

Struggling to integrate Angular with Django has been quite a challenge for me. After finally managing to make it work, I encountered yet another error. Each time I load the application, the following error message pops up: Error: [ng:areq] Argument ' ...

What is the best way to implement the addMore event in my custom slot components when working with Vue Formulate?

I need help customizing the 'add more' button for group repeatable fields in Vue Formulate. I have created a custom slot component that is functioning correctly, but I am struggling to determine the click event needed to add another field when th ...

Transforming the MUI CircularProgress into a half circle shape

After utilizing CirculaProgress, I was able to achieve the following: https://i.sstatic.net/Y0Seo.png Is there a simple method to transform it into a semicircle like shown here? https://i.sstatic.net/D8bKu.png ...

Unable to load JSON data model

I have been working on loading a JSON model and displaying it on the canvas, but I am encountering an issue where nothing is being drawn on the screen. Even when I try to use an alert inside the loader.load callback, the alert never shows up because the ca ...

Methods for breaking down a number into individual elements within an array

Suppose there is a number given: let num = 969 The goal is to separate this number into an array of digits. The first two techniques fail, but the third one succeeds. What makes the third method different from the first two? num + ''.split(&ap ...

Is it possible to update a URL in PHP without having to refresh the entire page by utilizing JavaScript?

Below is the JavaScript function I am using to create a URL: function reload(form){ var val1=form.dav.options[form.dav.options.selectedIndex].value; var val2=form.pathogen.options[form.pathogen.options.selectedIndex].value; var val3=form.topicF.options[for ...

How to programmatically open a new tab in Internet Explorer 7

I work on developing web applications using C#, ASP.NET 3.5, and Ajax 2.0. Query - While running Application_1 in Internet Explorer 7, I want to programmatically initiate the execution of Application_2 from Application_1 in a new tab, disregarding client ...

The $scope variables in ngDialog are not being updated when using ngModel fields in $dialog with scope: $scope

I'm currently facing an issue with a controller that uses ngDialog.open to create a dialog box. I've assigned scope:$scope and set variables using ng-model within the popup $dialog, but for some reason, these values are not getting set in the con ...

Is it possible to efficiently update the innerHTML of multiple div elements using a single function?

Upon clicking a button, I am dynamically updating the content of multiple divs using innerHTML. Currently, the button triggers a new video source to load, but I also want to change other types of content in different divs at the same time. I wonder if cha ...

Creating a jQuery accordion: A step-by-step guide

I'm currently working on building a dynamic accordion using jQuery where only one element can be open at a time. When a new element is opened, the previous one should close. I've managed to make it open and hide the button when opening it, but I ...

StaleElementReferenceError: The element reference is no longer valid

I am trying to extract the folderId values from the following code: { "folderType": 3, "createdDate": "02.09.2014 11:57:28.UTC", "modifiedDate": "02.09.2014 11:57:28.UTC", "folderName": "Enterprise", "folder ...

Adding a unique object to a different user class with cloud code on Parse.com

I need to incorporate the current user object ID array into a user's "followers" column in Parse, but because of security restrictions, I have to use cloud code. Unfortunately, I don't know much about JavaScript and could use some assistance. Her ...

Low resolution icons in Cordova using JQuery Mobile

Currently, I am working on a Cordova application and encountering an issue where the icons appear low resolution when running it on Android or a browser. I came across a solution online advising to add the following code snippet to the meta tag: <meta ...

mastering the nuances of jQuery event namespaces

Below are some code snippets to consider: $("#atc-button").bind("click.hctpAttach", function (e) { console.log("Add to cart button clicked.") }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ...

Exploring the process of locating text within an element using Selenium and Python

I'm looking to confirm the validity of the text 'Awaiting Review'. Can anyone provide guidance on how to locate this specific element among all the parent elements that are causing confusion? Any explanation on how it functions would be grea ...

Troubleshooting in ReactJS and NodeJS: Understanding the "Pass --update-binary to reinstall or --build-from-source to recompile" error

After moving a ReactJS + NodeJS project from one computer to another, I attempted to install dependencies by running npm install in the terminal. However, I received the following response: > [email protected] install /Users/Joshua/Projects/practi ...

Securing pages in Laravel and Vue JS: Restricting access to unauthorized users

I have some concerns about my project as it relies on local storage. What if someone figures out how to manipulate it and change roles and permissions set for the logged-in user? For example, if someone changed ['accounting'] to ['accounting ...