首页 > 解决方案 > 如何在 Cypress.io 中等待 WebSocket STOMP 消息

问题描述

在我的一项测试中,我想等待 WebSocket STOMP 消息。Cypress.io 可以做到这一点吗?

标签: websocketstompcypress

解决方案


如果您的应用程序正在建立您要访问的 websocket,您可以遵循以下基本流程:

  1. 从测试中获取对WebSocket实例的引用。
  2. 将事件侦听器附加到WebSocket.
  3. 返回一个Cypress PromiseWebSocket ,当您收到消息时该 Promise已解决。

在没有工作应用程序的情况下,这对我来说有点难以测试,但这样的事情应该可以工作:

在您的应用程序代码中:

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


推荐阅读