Cypress提取alert弹窗客户ID无法写入JSON文件问题求助
问题原因及修复方案
核心问题点
- 现有代码拆分字符串后未处理多余空格,提取到的ID会带前置空格,也没有做格式清洗
cy.on('window:alert')事件注册需要在触发alert的操作之前执行,否则会监听不到弹窗事件,导致后续写入逻辑完全不运行- 若
account_details.json文件初始为空或不存在,cy.readFile会直接报错打断流程 - 没有做异常捕获,无法定位具体失败环节
修正后代码
export function stripcustomerid() { // 提前注册alert监听,必须放在触发弹窗的操作之前调用 cy.on('window:alert', (txt) => { // 用正则匹配ID更稳定,不受文本内容小变动影响 const idMatch = txt.match(/customer id\s*:(\d+)/i) if (!idMatch) { throw new Error(`未在alert文本中匹配到客户ID,alert内容:${txt}`) } const customerId = Number(idMatch[1]) // 读取文件时设置默认空对象,避免文件不存在/为空时报错 cy.readFile('cypress/fixtures/account_details.json', { defaultValue: {} }).then((data) => { data.customerid = customerId // Cypress会自动将对象转成JSON,加spaces参数可以格式化JSON提升可读性 cy.writeFile('cypress/fixtures/account_details.json', data, { spaces: 2 }) }) }) }
使用注意事项
- 必须在触发弹窗的测试操作之前调用
stripcustomerid()函数,正确调用顺序示例:stripcustomerid() cy.get('#add-customer-button').click() // 触发alert的操作写在监听注册之后 - 若需要验证写入结果,可以在触发弹窗操作后追加校验逻辑:
cy.readFile('cypress/fixtures/account_details.json').its('customerid').should('be.a', 'number')
内容的提问来源于stack exchange,提问作者Manish B
相关产品推荐
相关产品推荐

