如何在Cypress.io中等待WebSocket STOMP消息

4

在我的一个测试中,我想等待WebSocket STOMP消息。Cypress.io能实现吗?

1个回答

3
如果您的应用程序正在建立WebSocket连接,您可以按照以下基本流程操作:
  1. 从测试中获取对WebSocket实例的引用。
  2. 将事件侦听器附加到WebSocket。
  3. 返回一个Cypress Promise,该Promise在WebSocket接收到消息时解决。

在没有工作应用程序的情况下,这有点难以测试,但类似于以下内容应该可以工作:

在您的应用程序代码中:

// 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
}

在您的 Cypress 测试代码中:
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)
  })
})


如果实现代码超出了我的控制范围 - 我还能在Cypress测试中拦截websocket消息吗(类似于cy.intercept(uri)的方式)? - Dzmitry Alifer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接