Cypress中BeforeEach执行异常,Promise处理问题求助
问题分析
你的核心问题在于createCustomerWithoutPID函数中的Promise没有正确解析cy.request的响应结果:
- 你创建的
new Promise没有调用resolve方法传递响应数据,导致Promise永远处于pending状态,await无法获取到结果,进而阻塞了beforeEach的后续执行 cy.request是Cypress的内置命令,本身遵循Cypress的异步队列机制,不能直接用空Promise包裹,需要手动处理响应的传递
修复方案
方案一:正确封装Promise(兼容async/await写法)
修改createCustomerWithoutPID函数,在cy.request的回调中调用resolve传递customerNumber:
export const createCustomerWithoutPID = async ( firstName: string, lastName: string, email: string, ): Promise<string> => { const env = Cypress.env('CYPRESS_ENV') return new Promise((resolve) => { cy.request({ method: 'POST', url: `http://test-data-service.${env}.corp.telenet.be/api/customer-accounts`, headers: { accept: 'application/json', 'Content-Type': 'application/json', }, body: { firstName, lastName, emailAddress: email, }, }).then((response) => { // 调用resolve传递customerNumber resolve(response.body.customerNumber) }) }) }
beforeEach代码可以保留原有的async/await写法,但要确保generateRequestID和generateJWTtoken也正确封装了Promise(如果内部使用Cypress命令,也要做类似的resolve处理):
beforeEach(async () => { const customerNumber = await createCustomerWithoutPID( firstName, lastname, email, ) cy.log(customerNumber) const requestId = await generateRequestID(customerNumber) const generateJWT = await generateJWTtoken(customerNumber, requestId) cy.visit( `https://www.uat.telenet.be/nl/create-profile/?flow=completeProfile&jwt=${generateJWT}`, ) cy.log('disable recaptcha') cy.turnOffRecaptcha() })
方案二:改用Cypress链式命令风格(更符合官方最佳实践)
Cypress本身的异步模型更适合链式调用,避免async/await与Cypress命令混用可能出现的顺序问题。重构相关函数返回Cypress.Chainable:
重构createCustomerWithoutPID
export const createCustomerWithoutPID = ( firstName: string, lastName: string, email: string, ): Cypress.Chainable<string> => { const env = Cypress.env('CYPRESS_ENV') return cy.request({ method: 'POST', url: `http://test-data-service.${env}.corp.telenet.be/api/customer-accounts`, headers: { accept: 'application/json', 'Content-Type': 'application/json', }, body: { firstName, lastName, emailAddress: email, }, }).then((response) => response.body.customerNumber) }
修改beforeEach为链式调用
beforeEach(() => { let customerNumber: string createCustomerWithoutPID(firstName, lastname, email) .then((num) => { customerNumber = num cy.log(num) return generateRequestID(num) // 确保该函数也返回Chainable或Promise }) .then((requestId) => generateJWTtoken(customerNumber, requestId)) .then((jwt) => { cy.visit( `https://www.uat.telenet.be/nl/create-profile/?flow=completeProfile&jwt=${jwt}`, ) cy.log('disable recaptcha') cy.turnOffRecaptcha() }) })
额外注意事项
- 如果
generateRequestID和generateJWTtoken内部也使用了Cypress命令,建议同样改成返回Cypress.Chainable,保持风格统一 - 避免在Cypress命令中混用原生async/await和Cypress的异步队列,容易出现执行顺序混乱的问题
内容的提问来源于stack exchange,提问作者user24006146
相关产品推荐
相关产品推荐

