skip to Main Content

I have created a script where I will generate a random word using this code.

    Alpha_Numeric() {
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    
        for (var i = 0; i < 10; i++)
          text += possible.charAt(Math.floor(Math.random() * possible.length));
    
          cy.log("site name: ",text);
        return text;
      }

And store the value into testdata.json using this code

        cy.readFile(filepath).then((obj)=>{
          obj.site=site_name;
          cy.writeFile(filepath,obj);
        })

During run time I will read this value from the json and use it in.

I will be following the same steps for 3 different testcases because the value which I have added once cannot be repeated.

The problem what I’m facing is for the first testcase the code is working properly and for the reaming two testcases what’s happening is, in the json file the value of ‘site’ is updated but during run time the older value is fetched IDK why.

Can anyone resolve this issue.

2

Answers


  1. The problem if you use cy.fixture() to read the file multiple time, this command is caching. It will only read from the disk once, there-after it will give the test the cached (old) value.

    Instead of cy.fixture() you can use cy.readFile() each time the test needs to use the values from testdata.json.

    See fixture#Loaded-just-once

    Please keep in mind that fixture files are assumed to be unchanged during the test, and thus Cypress loads them just once. Even if you overwrite the fixture file itself, the already loaded fixture data remains the same.

    If you wish to dynamically change the contents of a file during your tests, consider cy.readFile() instead.

    See also fixture#See-also

    See also
    .readFile() for a similar command without caching and with builtin retryability

    Login or Signup to reply.
  2. You can also modify testdata.json on the fly, something like

    const { alphaNumeric } = require('my-funcs.js')
    
    cy.fixture('testdata.json').then(data => {
      data.site = alphaNumeric();
    
      // test continues with new data
    

    If you wish you can also avoid importing by creating a Custom Command

    Cypress.Commands.add('alphaNumeric', () => {
            var text = "";
            var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        
            for (var i = 0; i < 10; i++)
              text += possible.charAt(Math.floor(Math.random() * possible.length));
        
              cy.log("site name: ",text);
            return text;
          })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search