mswjs / interceptors

Low-level network interception library.
https://npm.im/@mswjs/interceptors
MIT License
539 stars 123 forks source link

fix: add "address()" on mock Socket #549

Closed mikicho closed 5 months ago

kettanaito commented 5 months ago

Sharing our conversation from Discord:

WDYT about something like realSocket property in the MockSocket class? so in the address function we can do something like: if (mocked) {..} else this.realSocket.address()

That's tempting but I would recommend against it. realSocket introduces a state and I'd rather not have any state (or as little as possible state).

Instead, we know the mocked and passthrough contexts because we have methods respondWith() and passthrough(). Those methods can set the address function on the socket instance based on the context:

passthrough() {
  const realSocket = createConnection()
  // Fro actual connections, infer the address function.
  this.address = realSocket.address
}

respondWith(response) {
  this.address = () => addressFromResponse(response)
}
mikicho commented 5 months ago

@kettanaito I fixed this as suggested. I still think we need to separate the socket-related logic from the HTTP-specific one if we want to support more protocols, but that can wait for another PR.

I have a couple of questions before it's ready for merge from my side:

  1. Where should the tests I added be?
  2. What do you think about current fake values? Do you have a better idea?