Cypress using .as (alias) to store and validate against faker text

52 views Asked by At

I was wondering if it was possible to use Cypress' built in functionality .as to store some randomly generated text and then validate against it. I've tried various ways of handling this but I can't seem to get anything to work, any help would be appreciated

The code below is obviously incorrect but this is what I'm trying to achieve:

.type(faker.lorem.words()).as('fieldName')
      .should("have.value", cy.get('@fieldName'));

I'm using 'faker.lorem.words' to enter a randomly generated string into a field, which I'm then trying to store using an alias. I then want to validate that the field should have the value using an alias.

Any help would be great thank you!

1

There are 1 answers

0
Grace Rizzo On

Basically you just use cy.wrap() to create a aliasable value. Using type:static on the alias ensures that it's exactly the same value, although for a constant value it's probably not needed.

In one test

const words = faker.lorem.words()
cy.wrap(words).as('words', {type: 'static'})

// later

cy.get('@words')
  .then(words => {
    cy.get(some-selector).type(words)    // type should be end of chain
    cy.get(some-selector).should("have.value", words)
  })

In multiple tests in one spec file

Note that aliases are only good for the current test.

If you need to use the value across different tests, substitute Cypress.env()

const words = faker.lorem.words()
Cypress.env('words', words)

// later

cy.get(some-selector).type(Cypress.env('words'))    
cy.get(some-selector).should("have.value", Cypress.env('words'))

Across all specs in a run

You could save the data to a fixture in before()

// put this in cypress/support/e2e.js
before(() => {
  const words = faker.lorem.words()
  cy.writefile('cypress/fixtures/words.json', {words})
})

In the test:

it('uses words fixture', () => {
  cy.fixture('words.json').then(data => {
    cy.get(some-selector).type(data.words) 
  })

or

const data = require('cypress/fixtures/words.json')

it('uses words fixture', () => {
  cy.get(some-selector).type(data.words) 
  ...