Even when there is a change in value within the beforeEach hook, the original value remains unchanged and is used for dynamic tests

My current project setup: I am currently conducting dynamic tests on cypress where I receive a list of names from environment variables. The number of tests I run depends on the number of names in this list.

What I aim to achieve: My main goal is to manipulate the array containing the list in such a way that if it includes the word 'ALL' passed through the environment variable, I want to modify the array by adding all names obtained through an API call. This approach avoids the need to manually input each name individually.

The issue I am facing: Despite using beforeEach() before the test runs, the value within my array remains unchanged and still reflects the original value obtained from the environment variables. I suspect that the code outside it() and beforeeach(), but within describe(), executes first... However, even after the beforeEach() updates the array, the tests continue to use the outdated value sourced from the environment variable.

I intend to conditionally update my array based on the content passed in the environment variable "ALL" or specific names.

This excerpt shows my current code structure:

describe('[' + Cypress.env('TEAM') + ' - ' + Cypress.env('CLUSTER') + '] - ', () => {

    let dataPoolsArray: string[] = Cypress.env('DATAPOOLS').split(',') // directly fetched from env variable

    beforeEach(() => {
        cy.defaultLogin()

        if ( Cypress.env('DATAPOOLS') === 'ALL') { // Depending on the env variable, I want to modify the array value here
            dataPoolsArray.length = 0
            let i = 0
            cy.Integration_DataPool_findAll().then((getDataPoolsResponse) => {
                getDataPoolsResponse.body
                .forEach((dataPool: any) => {
                    dataPoolsArray.push(dataPool.name) 
                    cy.log('dataPoolsArray:  ' + dataPoolsArray[i])
                    i ++
                })
            })

        }

    })

    // Initial problem arises as only "ALL" is taken as the array value when running the test

    dataPoolsArray.forEach((poolName) => { 

        it('Data Model for pool: ' + poolName, () => {
            cy.log('Checking if datamodel loaded for the pool: ' + poolName)
            cy.sendPqlQueryToAnalysisConnectedToPool(poolName)
        })

    })


})

Any assistance provided would be greatly appreciated.

Answer №1

Issue: The challenge arises when attempting to dynamically generate test cases by looping through an array asynchronously populated within the beforeEach hook. Even if the code in the hook was synchronous (which it isn't), it executes after the test cases are generated.

Resolution: As far as I know, there is no alternative but to populate the dataPoolsArray array synchronously and outside of any hook. Mocha (and Cypress) mandates that suites (describe) and test cases (it) be registered synchronously.

That being said, one potential solution could involve generating the entire test file either before executing Cypress or preprocessing the test file itself somehow, as detailed in thisdocumentation.

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

Guide on establishing a connection with a TCP server and sending a JavaScript script to it

I am completely new to JS and node. I am using SkyX Pro, a telescope management software that has the capability to run a TCP Server on port 3040. By connecting with Netcat and providing it with Javascript starting with //* Javascript *//, I can control ca ...

When using Multer for file upload, the req.body returns as an empty object while req.file is undefined

I previously shared a problem I encountered while using multer for file upload in the MERN stack. Despite my attempts, I have not yet been able to resolve it. In my app, I am using both body-parser and multer. Here is the order of code in my index.js file: ...

Having trouble retrieving the state value of an array in React?

Having issues with ...this.state.users in React My React Code: handleChange(i, e) { const { name, value } = e.target; let users = [...this.state.users]; users[i] = { ...users[i], [name]: value }; this.setState({ users }); } Snippet from ...

The component "react-dnd-html5-backend" does not have a defined export called 'HTML5Backend'

What is the solution to resolve this issue? The error message states that 'react-dnd-html5-backend' does not have an exported member named 'HTML5Backend'. https://i.sstatic.net/QUZut.jpg ...

Managing Emitted Events in Vue.js Components within Components: A Guide

I have created a Toolbar Item component as follows: <template> <div class="flex cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 p-1 shadow-sm transition-all duration-300 hover:scale-110 hover:bg-black ho ...

Tips for emphasizing a searched item in V-data-table using VueJS

Is it possible to highlight a specific value in a v-data-table by searching for a particular word? Below is a snippet of my current code: EDIT: I am using the CRUD-Actions Example from the official Vuetify documentation. https://vuetifyjs.com/en/componen ...

CSS magic: Text animation letter by letter

I have a <div> with text. <div> to be revealed on the page one character at a time:</p> <div>, the animation should stop and display the full text instantly.</p> In summary, I aim to replicate an effect commonly seen in Jap ...

Is there a way to replace top-level environment variables with lower-level ones in a GitHub Actions .yml file?

I have encountered an issue with a .yml file in my CI/CD pipeline on Github Actions. I defined an env variable at the job level, and then attempted to reset it at the step level for a single step. However, the environment variable at the step level does no ...

Using TypeScript with React and Material-UI: Issue with undefined theme in createStyles()

Currently, I am delving into React with TypeScript and utilizing the Material UI framework for the frontend. In my quest to activate media queries, an error has crossed my path: Uncaught TypeError: Cannot read property 'up' of undefined ...

What is the best way to obtain clear HTTP request data in a component?

My service retrieves JSON data from the backend: constructor(private http: Http) { }; getUsers(): Observable<any> { return this.http.get('http://127.0.0.1:8000/app_todo2/users_list'); }; In the component, this data is processed: ng ...

Trigger the mousemove event only after the mouse click event has been activated

I need help with my code. I want an onmousemove event to occur when I click and move the mouse. Can someone assist me please? </head> <body> <img id="myImgId" alt="" src="Chrysa ...

Retrieving the value of a nested JSON object with a dynamic key

Currently, I am attempting to log a JSON key that is dynamic to the console. However, there is another nested object inside the main object that I also need to access a value from. The key of this nested object contains special characters, so I have been u ...

Updating the Background Image Based on Text Input in JavaScript

Struggling to utilize the text entered into a text input field as a background image URL. Ensuring it is valid is key. This snippet displays what has been attempted so far... CSS: body { margin: 0px; padding: 0px; border: 0px; } .bgimg { backgr ...

Minimize the entire project by compressing the .css, .js, and .html files

After recently incorporating Grunt into my workflow, I was thrilled with how it streamlined the process of minifying/concatenating .css files and minifying/uglify/concatenating .js files. With Grunt watch and express, I was able to automate compiling and ...

Modifying an onClick handler function within a react element located in a node module, which points to a function in a prop declared in the main Component file

I have successfully implemented the coreui CDataTable to display a table. return ( <CDataTable items={data} fields={fields} ... /> ) Everything is working smoothly, but I wanted to add an extra button in the header of the C ...

Inputting data types as arguments into a personalized hook

I am currently developing a Next.js application and have created a custom hook called useAxios. I am looking to implement a type assertion similar to what can be done with useState. For example: const [foo, setFoo] = useState<string>(''); ...

What is the best way to reset react-id-swiper every time an event handler is triggered in a React application?

I have incorporated the react-id-swiper module into my React project to create a dynamic image slider. By setting onClick event handlers on buttons with different id attributes, I trigger API calls that update the state and populate the ImageSlider compone ...

"Encountering a 404 error on newly published content, post build phase, with the integration of Next

My main objective is to enable the addition of new posts to the CMS (Sanity.io) post-build, and have the website display the received data on a designated slug through dynamic routes. While everything functions smoothly in the development environment, I e ...

How can I automatically submit a form upon page load with AJAX and receive the result in HTML format?

Attempting to automatically submit a form when the page loads using ajax and then retrieve the HTML (consisting of multiple divs that will be echoed on the AJAX URL) back to my AJAX page. Firstly, the code successfully auto submits the form but fails to t ...

Exploring additional parameters within express.js

I'm currently working on creating an email sender that includes all necessary components such as 'from', 'to', 'subject', 'textBody', etc. However, I am facing a challenge in setting optional parameters in expre ...