Cypress React E2E测试中MongoDB Realm后端调用Promise未发送问题
Cypress E2E测试中MongoDB Realm后续调用丢失、Promise挂起问题
环境配置
- TypeScript
- React v17
- MongoDB Realm (realm-web) v1.7
- Cypress v12.11.0
问题现象
- 测试用例中第二次点击
property-submit按钮触发handleCreateProperty函数时,其中调用的insertPropertyPromise始终处于pending状态,请求从未到达后端 - MongoDB Realm日志显示登录成功,前两次后端调用(
getContext、getDashboardStatistics)正常,但后续所有callFunction调用均丢失 - 在Cypress UI中重新加载页面后,
getContext请求也无法到达后端 - 手动测试流程完全正常,尝试调整Cypress配置、更换浏览器、禁用Chrome安全设置等操作均无效,Wireshark未捕获到相关请求
相关代码片段
测试用例代码
// 替换为实际测试用例代码
handleCreateProperty函数代码
// 替换为实际handleCreateProperty函数代码
insertProperty及关联函数代码
// 替换为实际insertProperty及关联函数代码
cypress.config.ts配置
// 替换为实际cypress.config.ts代码
排查与解决方案
重置Realm实例状态
Realm Web客户端实例在Cypress测试环境中可能存在状态污染,建议在每次测试前重新初始化实例,避免复用全局实例:beforeEach(() => { cy.visit('/'); // 重新初始化Realm App实例 window.realmApp = new Realm.App({ id: 'YOUR_REALM_APP_ID' }); });排除WebSocket拦截干扰
Realm Web默认通过WebSocket与后端通信,Cypress的网络拦截逻辑可能破坏WebSocket连接。可在Cypress配置中禁用相关拦截:// cypress.config.ts export default defineConfig({ e2e: { setupNodeEvents(on, config) { on('before:browser:launch', (browser, launchOptions) => { launchOptions.args.push('--disable-features=NetworkService,NetworkServiceInProcess'); return launchOptions; }); }, }, });确保测试异步操作等待正确
测试中需明确等待异步操作完成,避免Cypress执行时序导致的状态异常:// 点击提交按钮后,等待成功提示出现 cy.get('[data-testid="property-submit"]').click(); cy.get('[data-testid="property-created-alert"]').should('be.visible');清除测试会话缓存
每次测试前清除浏览器本地存储和Cookie,避免Realm会话残留影响后续调用:beforeEach(() => { cy.clearLocalStorage(); cy.clearCookies(); cy.visit('/'); });升级Realm Web版本
realm-web v1.7与Cypress v12.x可能存在兼容性问题,尝试升级至最新稳定版:npm install realm-web@latest
问题总结
两次MongoDB Realm后端调用正常执行后,所有后续后端调用均丢失,Promise始终处于pending状态(既不resolve也不reject)。
内容的提问来源于stack exchange,提问作者Daniel Robin
相关产品推荐
相关产品推荐

