0

I'm using Protractor to automate some tests.

In spec 1, I do some actions and collect some information in a CSV file:

describe("Spec 1", function () {

  for (let i of some_useful_array) {
    it("does some business", async function () {
      saveData(someData)
    })
  }

  function saveData(someData) {
    fs.appendFile("./file.csv", "\n" + someData, (err) => {
      if (err) {
        console.log(err);
      }
    })
  }

})

In spec 2, I would like to use this information:

var myFile= fs.readFileSync('./file.csv');

const data = parse(myFile, {
  columns: true,
  skip_empty_lines: true
})

describe("Spec 2", function () {

  for (let i of some_other_useful_array) {
    it("does some other business", function () {
      console.log(data) // logs an empty array ([]) when run in the same execution than spec 1
    })
  }
})

It works like a charm when I run spec 1 and spec 2 separately, but it doesn't work when I run them in the same execution. I guess I need to close something, I have tried some things (for example fs.close()) but none of these worked.

Any idea?

EDIT: I tried something: copy file.csv to file2.csv in spec 1, and use file2.csv in spec 2. It seems to work a bit better. Nasty workaround though, but good enough until I bump into a better solution.

Zoette
  • 1,241
  • 2
  • 18
  • 49

1 Answers1

1

fs.appendFile is asynchronous, meaning that javascript doesn't wait until it finishes it's task. Basically spec 2 is ran before csv is fully created. This probably won't be an issue when you run the real spec which will take at least a few seconds. But to be safe, you better go with fs.appendFileSync which does the same but doesn't schedule another task until this one is done

another ways for solving this behavior described here https://stackoverflow.com/a/45463672/9150146

Sergey Pleshakov
  • 7,964
  • 2
  • 17
  • 40