pmiranda
pmiranda

Reputation: 8420

Cypress custom Commando with cy.origin inside

I'm trying to do this command:

Cypress.Commands.add('login', (userId, password) => {
  cy.origin('https://some-sso.page', () => {
    cy.get('input[placeholder="UserID"]').type(userId);
    cy.get('input[placeholder="Password"]').type(password0);
    cy.contains('SIGN IN').click();
  });
});

And call it with:

cy.login('someUser', '12345');

But I get the error:

userId is not defined
Variables must either be defined within the cy.origin() command or passed in using the args option.

I tried to add some const inside the cy.origin because without the custom command was working, like this:

cy.origin('https://some-sso.page', () => {
  const userId = 'someUser';
  const pass = '12345';

  cy.get('input[placeholder="User ID"]').type(userId);
  cy.get('input[placeholder="Password"]').type(pass);
  cy.contains('SIGN IN').click();
});

cy.get('#div > section').contains('It works');

How could I do that custom Command?

Upvotes: 1

Views: 985

Answers (1)

Fody
Fody

Reputation: 31862

The cy.origin() command creates a sandbox, which prevents closures from working - you have attempted to use the custom command parameter as a closure variable inside the cy.origin().

Any variables need to be explicitly passed in as a single parameter object, like this

Cypress.Commands.add("login", (userId, password) => {
  cy.origin("https://some-sso.page",
    { args: { userId, password } },             // variables passed in
    ({ userId, password }) => {                 // inside, unwrapped (destructured)

      cy.wrap(userId).should("eq", "someUser"); // passes

      cy.get('input[placeholder="UserID"]').type(userId);
      cy.get('input[placeholder="Password"]').type(password); 
      cy.contains("SIGN IN").click();
    }
  );
});

Upvotes: 3

Related Questions