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

时间:2018-06-17 09:00:34

标签: websocket stomp cypress

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

1 个答案:

答案 0 :(得分:1)

如果您要访问的网络套接字是由您的应用程序建立的,则可以执行以下基本过程:

  1. 从测试内部获取对WebSocket实例的引用。
  2. 将事件监听器附加到WebSocket
  3. 返回Cypress 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
}

在您的赛普拉斯测试代码中:

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