I have a JSON file that contains a value that I need to update as a step of a Playwright test as well as containing other values that need to remain unchanged. I have found a solution but it’s not working for me because it "Cannot file module {file}". The file path I’m giving is definitely correct.
My json file is called temp.json and contains:
{
"updateThis": "Original Value",
"dontUpdateThis": "Static Value"
}
This is the Playwright test:
const { test, expect } = require('@playwright/test');
const fs = require('fs')
const filename = 'tests/testdata/temp.json'
const data = require(filename);
test('update json key value', async() => {
data.updateThis = "New Value"
fs.writeFile(filename, JSON.stringify(data), function writeJSON() {
console.log(JSON.stringify(data));
console.log('writing to ' + fileName);
})
})
Thanks
2
Answers
I’d suggest a few changes:
fs.writeFile
rather than the old school callback version. This ensures your test function waits for the operation to complete before ending.npx playwright test
.__dirname
in your path to ensure correct path resolution regardless of where you run the test from.path.join
instead of hardcoding delimiters so your code is OS agnostic.tests/foo.test.js:
Sample run showing the updated value:
That said, tests should be idempotent, so they probably should not be writing files in most cases. So even if you have the tool you may not want to use it exactly like this.
Use
writeFileSync
orawait fs.writeFile()