首页 > 解决方案 > 有时 cypress 在通过 websocket 调用获取新信息时似乎阻止了 DOM 的更新

问题描述

我通过打开一个页面

cy.visit('https://localhost:9099/test')

该页面会自动为服务器设置一个 websokcet 并发送一些得到回答的“问题”。当回答时,页面中的 javascript 代码会更新 DOM/页面。

我遇到的问题是 DOM/页面并不总是更新,并且

cy.get('#ID', {timeout:40000})

失败。

柏树会以某种方式干扰页面代码吗?几年来,我使用 Selenium 执行了相同的测试,并且页面始终表现良好。

标签: websocketcypress

解决方案


赛普拉斯在执行命令之前尝试等待页面完成加载,因此在页面加载检查中可能不会注意到 websocket 交互。

如果你知道最后一个 websocket 消息,你可以等待它。

这是一个示例如何在 Cypress.io 中等待 WebSocket STOMP 消息

应用

// assuming you're using stomp-websocket: https://github.com/jmesnil/stomp-websocket

const Stomp = require('stompjs');

// bunch of app code here...

const client = Stomp.client(url);
if (window.Cypress) {
  // running inside of a Cypress test, so expose this websocket globally
  // so that the tests can access it
  window.stompClient = client
}

测试

cy.window()         // yields Window of application under test
.its('stompClient') // will automatically retry until `window.stompClient` exists
.then(stompClient => {
  // Cypress will wait for this Promise to resolve before continuing
  return new Cypress.Promise(resolve => {
    const onReceive = () => {
      subscription.unsubscribe()  // clean up our subscription
      resolve()                   // resolve so Cypress continues
    }
    // create a new subscription on the stompClient
    const subscription = stompClient.subscribe("/something/you're/waiting/for", onReceive)
  })
})

推荐阅读