mercredi 17 février 2021

Cypress: Select random enum value

I've got a bunch of enums in my Cypress tests, and I want to randomize some of them. When I'm using Kotlin, for instance, it's a no-brainer. However, I haven't been able to with Cypress/TypeScript and my very limited knowledge of the language.

The enum can have the following values: Purpose.BUILD, Purpose.BUY, Purpose.REBUILD

Here's what I've got so far, picked from somewhere I cannot remember at this moment (maybe StackOverflow?):

randomEnum<T>(anEnum: T): T[keyof T] {
  const enumValues = Object.keys(anEnum)
    .map(n => Number.parseInt(n))
    .filter(n => !Number.isNaN(n)) as unknown as T[keyof T][]
  const randomIndex = Math.floor(Math.random() * enumValues.length)
  return enumValues[randomIndex];
}

Called with:

const Purpose = ProsjektfinansieringTO.FinansieringsProdukterEnum;

// Get a random value for Purpose:
let Purpose: FinansieringsProdukterEnum = this.randomEnum(Porpose);
// Select the apporpriate choice on the page:
purposePage.setPurpose(purpose);         // Doesn't work
//purposePage.setPurpose(Purpose.BUY);   // Works.
   

As far as I can see, the randomEnum() function doesen't return an enum. Since the line below, which is commented out, works I believe the error to be with the randomEnum() function.

Any hints? What am I missing? Is it really this complicated?




Aucun commentaire:

Enregistrer un commentaire