如何解决Playwright中toMatchAriaSnapshot的双引号兼容错误?
解决Playwright toMatchAriaSnapshot动态文本引号兼容问题
核心思路
根据动态文本是否为空,动态生成带引号/不带引号的快照条目,同时避免YAML解析报错。
方案一:用三元表达式直接生成对应行
// 拼接动态内容 const dynamicContent = (error["login"] ?? "") + messages["login"] + " *"; // 根据内容是否为空生成对应的text行:空时不带引号,非空时用双引号包裹 const textEntry = dynamicContent ? `- text: "${dynamicContent}"` : `- text:`; await expect(page.locator('#contract')).toMatchAriaSnapshot(` - dialog: - document: - heading "Add" [level=5] - button "Close" ${textEntry} - textbox `);
方案二:封装辅助函数处理文本
如果需要复用逻辑,可以写个小函数统一处理:
function getFormattedTextEntry(content) { if (!content) return "- text:"; // 用双引号包裹非空内容,避免YAML解析嵌套映射错误 return `- text: "${content}"`; } const dynamicContent = (error["login"] ?? "") + messages["login"] + " *"; await expect(page.locator('#contract')).toMatchAriaSnapshot(` - dialog: - document: - heading "Add" [level=5] - button "Close" ${getFormattedTextEntry(dynamicContent)} - textbox `);
原理说明
- 当
dynamicContent为空时,生成- text:,符合Playwright期望的无引号格式,不会触发报错; - 当内容非空时,用双引号包裹文本,让YAML将整个内容识别为字符串,避免把文本里的冒号等特殊字符解析成嵌套映射,解决报错问题。
内容的提问来源于stack exchange,提问作者Elikill58
相关产品推荐
相关产品推荐

