user17508887
user17508887

Reputation: 57

Calling a class from another file in Cypress

I have a file helpers.js with those contents:

export default {
    green:'4bdd33',
    orange:'ff7900',
    red:'d92632',
  };

I want to convert it to a class , I try to do that:

class colors {
        green='4bdd33'
        orange='ff7900'
        red='d92632'
      }
export default colors;  

if that is the right way. in the body of the cypress test how can I import this the calss and using its properties. I do that in the cypress test file :

import colors from '../../support/helpers';

and in the body of test i call its properties in this way

 cy.get('selector').contains(colors.green)

but Cypress throw an error in this way.

Upvotes: 1

Views: 2008

Answers (2)

agoff
agoff

Reputation: 7150

Sebastiano's answer is the correct one. In this case, it doesn't make much sense to create a class to house constants. But if you did want to keep colors as a class, you'd simply have to instantiate it before calling it.

const myColors = new colors()
cy.get('selector').contains(myColors.green)
// or...
cy.get('selector').contains(new colors().green)

As an aside, it is recommended that classes begin with an uppercase -- Colors instead of colors. When naming classes this way, you can have the class in uppercase and the variable instance in lowercase.

export class Colors {...};

const colors = new Colors();

Upvotes: 2

Sebastiano Schwarz
Sebastiano Schwarz

Reputation: 1146

Why do you want to use a Class? Instead of using a Class you could simply export a JavaScript Object in your helpers.js file like:

export const colors = {
   green: '4bdd33',
   orange: 'ff7900',
   red: 'd92632'
};

And in your Cypress test file you can import colors with:

import { colors } from '../../support/helpers';

Then you can use colors as you already described in the question.

Upvotes: 3

Related Questions