node.jsfilecypress

cy.readFile results in timeout?


I am trying to read an JSON file that I have just written with another test in the same cypress project. However when it tries to read the file it times out after 4000 milliseconds.

Has anyone experienced this before? How could I solve it?

I have tried increasing the time out by giving it a settings object but that doesn't increase the time out time. I thought it might be a file permissions issue but that doesn't seem to be it either.

I am running on Mac but tried the same project on Windows with the same result.

  before('grab generated user data', function (){
      let data = cy.readFile("Generated User/Cypress test 131.json", {log:true, timeout: 180000});
}

I expect it to just give back the parsed JSON object. As it says in the Cypress docs. (https://docs.cypress.io/api/commands/readfile.html#Syntax)


Solution

  • I ended up creating a data.json with cy.createFileSync(). When I want to read the file instead of using cypresses cy.readFile() function I created a cypress task that uses the fs library to read the file.

    I am leaving you with the code snipped of the task I used to read the file.

    const fs      = require('fs');
    const request = require('request');
    
    module.exports = (on, config) => {
        on('task', {
            //  Cypress task to get the last ID
            getLastId: () => {
                //  Make a promise to tell Cypress to wait for this task to complete
                return new Promise((resolve) => {
                    fs.readFile("data.json", 'utf8', (err, data) => {
                        if (data !== null && data !== undefined) {
                            data = JSON.parse(data);
                            if (data.hasOwnProperty('last_id')) {
                                resolve(data.last_id);
                            } else {
                                resolve("Missing last_id");
                            }
                        } else {
                            resolve(err);
                        }
                    });
                });
            }
    

    Calling this function would be as simple as

     let id = 0;
    
                before('grab generated user data', function (){
                    cy.task('getLastId').then((newID)=>{
                        id = newID;
                    });
                });