Home > OS >  Cypress - Use Chance JS to generate Data and store that Data for use later
Cypress - Use Chance JS to generate Data and store that Data for use later

Time:06-18

Essentially what I want to do is generate a name using ChanceJS for a test case within cypress, but in a separate file / test case I want to be able to recall that name that I generated earlier so I can select it / check it exists.

I have cut down these code snippets a fair bit so they wont make total sense.

I have tried having my own file with a constant in it called constants.js

    require('chance')
 export const constants = {
    ITEM: chance.word()
  }

and then having something like this in a test file where I add an item using the random name as its name

import { constants } from '../constants';
//Add Item
it('Add a Item', function(){
cy.pass_credentials()
cy.get('.dx-datagrid-toolbar-button > .dx-button-content > .dx-icon').click({force: true})
cy.get('[id$=_Name]').type(constants.ITEM) // using my random name for the item name
}

and then later I try to use it again to select the item in a separate file as the data I added in the previous file is now being used as part of this other piece of data

import { constants } from '../constants';
it('Add Data', function(){
cy.pass_credentials()
cy.get('[id$=_TaskId]').type(constants.ITEM)    //typing my random name in so I can select it as its now part of a drop making up this new piece of data  
cy.contains(constants.ITEM).type('{enter}')     //trying to press enter so I select my item
}

But the issue I am having is that it is generating a new random name which means im trying to select something that is not there. I'm not sure if every time I import it on a new file to be used that's what's causing it to re-generate?

I guess I could do with some pointers or a better solution to my issue.

CodePudding user response:

One way would be to generate the item the first time and save it in Cypress.env() variable and then use it through out your test. Cypress.env() can be accessed by any tests throughout and also one value would be passed to all the tests for that execution cycle.

import {constants} from '../constants'
//Add Item
it('Add a Item', function () {
  Cypress.env('uniqueItem', constants.ITEM) //Random item is set for this test run
  cy.pass_credentials()
  cy.get('.dx-datagrid-toolbar-button > .dx-button-content > .dx-icon').click({
    force: true,
  })
  cy.get('[id$=_Name]').type(Cypress.env('uniqueItem')) // types in the item
})

You test in next test suite. You don't need to call the import statements here and directly use the value using the Cypress.env('uniqueItem').

it('Add Data', function () {
  cy.pass_credentials()
  cy.get('[id$=_TaskId]').type(Cypress.env('uniqueItem'))
  cy.contains(Cypress.env('uniqueItem')).type('{enter}')
})
  • Related