我有一个 JSON 文件,其中包含需要作为 Playwright 测试步骤进行更新的值,以及需要保持不变的其他值。我找到了一个解决方案,但它对我不起作用,因为它“无法文件模块 {file}”。我给出的文件路径绝对正确。
我的 json 文件名为 temp.json 并包含:
{
"updateThis": "Original Value",
"dontUpdateThis": "Static Value"
}
这是剧作家测试:
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);
})
})
谢谢
我建议一些改变:
fs.writeFile
的承诺版本而不是旧的学校回调版本,确保您的测试函数在结束之前等待操作完成。npx playwright test
兼容。path.join
而不是硬编码分隔符,这样你的代码就与操作系统无关。测试/foo.test.js:
import fs from "node:fs/promises";
import path from "node:path";
import {test} from "@playwright/test";
import data from "./testdata/temp.json";
const filename = path.join("tests", "testdata", "temp.json");
test("update json key value", async () => {
data.updateThis = "New Value";
await fs.writeFile(filename, JSON.stringify(data));
});
显示更新值的示例运行:
$ 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