Ajax调用后Cypress如何正确定位更新后的HTML元素
Cypress测试Ajax动态内容失败的问题与解决方法
场景说明
我有一个通过Ajax调用处理的搜索输入框和结果展示区域。用户输入关键词后,Ajax调用后端返回HTML字符串,JS处理器会将返回的HTML追加到结果展示区域。
测试步骤
- 搜索输入框基于浏览器定位自动填入Vancouver
- 页面显示结果:Welcome to Vancouver
- 在搜索输入框中输入Calgary
- 预期结果:页面显示Welcome to Calgary
原测试用例代码
// Test case Cypress.Commands.add('assessHeadingInfo', (options) => { cy.fixture('selectors/index-page').then((selectors) => { cy.xpath(selectors.head_info).then((heading) => { cy.searchForArea('Calgary'); // 输入关键词并执行搜索的步骤 cy.get(heading) .children('h1') .should('be.visible'); cy.get(heading) .children('h1') .invoke('text') .should('equals', 'Welcome to Calgary'); }); }); });
测试报错
AssertionError Timed out retrying after 4000ms: expected 'Welcome to Vancouver' to equal 'Welcome to Calgary'
异常现象
截图显示页面已经正确显示Welcome to Calgary,但测试无法识别该内容。尝试添加cy.wait()等等待操作后问题仍未解决。
解决方案
在@jhelguero的帮助下,找到两种可行的解决方法:
方案1:使用cy.contains定位元素
cy.contains('h1', 'Welcome to Calgary') .should('be.visible');
原因:原代码将测试步骤放在cy.xpath(selectors.head_info).then((heading) => {...})回调中,cy.get(heading)捕获的是Ajax请求完成前的旧元素(即显示Welcome to Vancouver的元素),后续即使页面元素更新,测试仍在操作旧的DOM元素引用。
方案2:拆分定位与断言步骤
cy.searchForArea('Calgary'); cy.xpath(selectors.head_info) .children('h1') .should('have.text', 'Welcome to Calgary');
写法总结
正确写法
cy.xpath({selector}).should('have.text','ABC'); cy.xpath({selector}).find('h1').should('have.text', '123');
错误写法
cy.xpath({selector}).then((ele) => { cy.get(ele).should('have.text', 'ABC'); cy.get(ele).find('h1').should('have.text', '123'); });
内容的提问来源于stack exchange,提问作者TommyDo
相关产品推荐
相关产品推荐

