Playwright测试中更新JSON文件遇‘无法找到模块’问题求助
解决Playwright测试中更新JSON文件时的"Cannot find module"错误
问题复现
你尝试在Playwright测试中更新temp.json的updateThis字段,但运行时出现Cannot find module {file}错误,且已确认文件路径无误。相关文件和代码如下:
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); }) })
错误原因分析
- 相对路径解析问题:
require()的路径是基于Node进程的当前工作目录,而非测试文件所在目录。如果运行测试时的工作目录不是项目根目录,相对路径会失效。 - 模块缓存干扰:
require()加载JSON后会缓存内容,即使文件后续被修改,下次require仍会读取缓存,同时也可能因缓存逻辑导致路径解析异常。 - 变量拼写错误:代码中
console.log('writing to ' + fileName)的fileName应为filename(大小写不一致),虽然这不是模块找不到的直接原因,但会导致后续日志报错。
解决方案
推荐使用绝对路径+fs模块读取/写入的方式,彻底避免路径和缓存问题,同时修复拼写错误:
修改后的测试代码
const { test, expect } = require('@playwright/test'); const fs = require('fs'); const path = require('path'); // 生成绝对路径:__dirname表示当前测试文件所在目录,确保路径始终正确 const filename = path.resolve(__dirname, './testdata/temp.json'); test('update json key value', async() => { // 用fs读取文件并解析为JSON对象,避免require缓存 let data = JSON.parse(fs.readFileSync(filename, 'utf8')); // 更新目标字段 data.updateThis = "New Value"; // 同步写入文件(适合测试场景,不会阻塞异步流程),格式化JSON便于阅读 fs.writeFileSync(filename, JSON.stringify(data, null, 2)); console.log(JSON.stringify(data, null, 2)); console.log('writing to ' + filename); })
可选:异步写入风格(更贴合Playwright异步特性)
如果偏好异步操作,可使用fs.promises:
const { test, expect } = require('@playwright/test'); const fs = require('fs').promises; const path = require('path'); const filename = path.resolve(__dirname, './testdata/temp.json'); test('update json key value', async() => { const fileContent = await fs.readFile(filename, 'utf8'); let data = JSON.parse(fileContent); data.updateThis = "New Value"; await fs.writeFile(filename, JSON.stringify(data, null, 2)); console.log(JSON.stringify(data, null, 2)); console.log('writing to ' + filename); })
关键优化点
path.resolve(__dirname, ...):生成绝对路径,彻底解决相对路径依赖工作目录的问题。fs.readFileSync/fs.promises.readFile:直接读取文件内容,绕开require的模块缓存,确保每次获取最新的JSON数据。JSON.stringify(data, null, 2):格式化输出JSON,保留缩进,便于查看文件修改结果。- 修复变量拼写错误:统一使用
filename变量名。
内容的提问来源于stack exchange,提问作者Lank
相关产品推荐
相关产品推荐

