skip to Main Content

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


  1. I’d suggest a few changes:

    • Use the promise version of fs.writeFile rather than the old school callback version. This ensures your test function waits for the operation to complete before ending.
    • Use modules for tests so they’re compatible with npx playwright test.
    • Use __dirname in your path to ensure correct path resolution regardless of where you run the test from.
    • Use path.join instead of hardcoding delimiters so your code is OS agnostic.

    tests/foo.test.js:

    import fs from "node:fs/promises";
    import path from "node:path";
    import {test} from "@playwright/test"; // ^1.42.1
    import data from "./testdata/temp.json";
    
    const filePath = path.join(__dirname, "testdata", "temp.json");
    
    test("update json key value", async () => {
      data.updateThis = "New Value";
      await fs.writeFile(filePath, JSON.stringify(data));
    });
    

    Sample run showing the updated value:

    $ npx playwright test tests
    
    Running 1 test using 1 worker
    
      ✓  1 tests/foo.test.js:8:5 › update json key value (11ms)
    
      1 passed (219ms)
    $ cat tests/testdata/*.json
    {"updateThis":"New Value","dontUpdateThis":"Static Value"}
    $ tree tests
    tests
    ├── foo.test.js
    └── testdata
        └── temp.json
    
    1 directory, 2 files
    

    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.

    Login or Signup to reply.
  2. Use writeFileSync or await fs.writeFile()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search