cypress-io / cypress

Fast, easy and reliable testing for anything that runs in a browser.
https://cypress.io
MIT License
47.01k stars 3.18k forks source link

Share value from `before:spec` to `spec` in order to use value in tests #22833

Open alexniculae opened 2 years ago

alexniculae commented 2 years ago

Current behavior

Hello team,

Asked the below in a Q&A Discussion, but as there was no answer and I cannot find anything online, I'm trying here as well.

Q: Is it possible to share a value from the Before Spec API to the actual spec, so it can be used in the tests?

For example I tried to do it by leveraging the config object of Cypress and trying to create a new Cypress env var:

const {someFunc} = require('./some-func');

module.exports = (on, config) => {
  return on('before:spec', async () => {
    return someFunc().then((response) => {
      config.env.RESPONSE = response;
      return config;
    });
  });
}

Unfortunately I cannot get this to work, but I'm not sure if

Desired behavior

A solution for this or any other suggestions (that use the before:spec) would be great! πŸ™‚

It'd also be great if there would be a way to also pass a value FROM the spec file TO the before:spec

Cypress Version

"cypress": "9.6.1"

tbiethman commented 2 years ago

@alexniculae sharing data between the before:spec event and the spec itself (or vice versa) is not possible today. Is there a reason why before:spec needs to be used in your case? Your example seems like it'd be perfect as a before hook in a spec helper, but I'm probably missing some context.

alexniculae commented 2 years ago

@tbiethman, glad that you asked about the use for this request.

As an example, let's say we have 100 spec files that we want to run in parallel on 5 machines/runners.

The only major issue we need to overcome in order to do this is have a semaphore system for our test users, in order to not generate conflicts in these parallel runs.

In our example, let's say we have 10 users that are available for us to use in the specs

I have tried to find some examples or any documentation about this being done with Cypress but could not find any.

The logic I thought of:

The limitations I am hitting against:

Any input would be appreciated

Thank you