lensesio / cypress-websocket-testing

Test WebSocket connections with Cypress
Apache License 2.0
83 stars 12 forks source link

Open websocket -> Do something -> assert message #3

Closed twgraham closed 4 years ago

twgraham commented 4 years ago

Great work on this library!

Could you advise how the following use case might be approached?

My websocket sends notifications in realtime - it doesn't send notifications that might exist before it was opened.

A flow might look like:

  1. User opens app and connects to websocket
  2. User clicks around performing actions
  3. Messages are sent over the socket due to these actions

I've tried to open the socket and alias the promise created by myStream.toPromise() (this doesn't work too well with cypress).

dsebastian commented 4 years ago

Hi @twgraham . What you need to do in your case is first open the connection in your test using cy.stream(config) and decide what event will complete the stream such that it closes at some point. (see example in Readme) Then you start your automated clicks using the normal cypress mechanisms and check the results. But again, it's important that there is an event (time, amount of clicks etc) that will close the stream. Have a look at https://www.learnrxjs.io/operators/filtering/takeuntil.html to see different ways to trigger the socket closing. Let me know if it worked or if you have any other questions.

twgraham commented 4 years ago

Thanks @dsebastian .

What I ended up doing was opening a stream with some filters then assigning it to a promise. I then would perform some actions, and have cypress wrap (and wait) for the promise after.

e.g.

cy.stream<Message>().then((ws) => {
            const socketMessageAsync: Promise<Message> = sub.pipe(
                doSomething(),
                andThen(),
                somethingElse(),
                takeUntil(timer(4000))
            ).toPromise()

            cy.get('button').contains(/Lorem Ipsum/i)
            .click()
            .findByRole('alert').should('contain', 'You clicked lorem ipsum')
            .logout()

            cy.wrap<Promise<Message>, Message>(socketMessageAsync)
            .then((message) => {
                doSomethingWithResult(message)
            })
        })