httptoolkit / mockttp

Powerful friendly HTTP mock server & proxy library
https://httptoolkit.com
Apache License 2.0
781 stars 88 forks source link

Doc request: websocket example please #77

Open OnkelTem opened 2 years ago

OnkelTem commented 2 years ago

Sorry if it's actually covered somewhere in the docs, I failed to find it.

Could you please point out on the proper place in the docs or provide a basic example on how to mock a websocket service?

Use case: a front-end script wants to talk to a websocket server and we mock it using mockttp.

Thanks in advance!

pimterry commented 2 years ago

Right now, websockets aren't well supported yet. The basic infrastructure is all in place to handle websockets and define rules that mock them, but there's not many rules available yet, that a work in progress as we speak. I've got plans for this, but it's going to require a little design work on the API, since the series of steps is fundamentally a different flow to the request/response model from HTTP.

In practice it's probably going to be similar to the way MockRTC defines chains of mocking steps for WebRTC, as here: https://github.com/httptoolkit/mockrtc/#mocking-webrtc-traffic.

The few websocket behaviours you can use today with Mockttp are listed here: https://httptoolkit.github.io/mockttp/classes/WebSocketRuleBuilder.html.

In general, the way you'd use this is like:

mockServer.forAnyWebsocket() // Start building a websocket rule
  .forHostname('example.com') // Match anything you like
  .thenPassThrough() // Define some behaviour

The behaviours are fairly limited at the moment though.

Do you know what kind of behaviours you'd like? Any thoughts on what you'd like that API to look like?

OnkelTem commented 2 years ago

Thank you very much, I'll try it and write back.

Currently, I need just a basic thing. As I said, I'm developing a scripts injector. And while developing a particular script (being injected) it would be cool to simply reload the page whenever the original script changes on disk. And the most obvious way I observe now would be to open a websocket in the mitm-part, and listen to it from the injected script. Whenever the underlying script is changing, mitm script can send a notification about it to the injected script.

Omg, so many words.

Here is an ugly picture of how it may look like :)

image

And so I just need a way to send a message through an existing websocket connection.

OnkelTem commented 2 years ago

An example of using this beautiful tool:

https://www.youtube.com/watch?v=9gpQZZbrGPk

I don't go into details in this particular video, but I plan to make another show-and-tell one.

pimterry commented 2 years ago

Awesome! Very cool :+1: