Comments (7)
That sounds great. Thanks for being open to the feedback. 🙏
from interceptors.
Hi, @nzakas. Thanks for suggesting this.
Just throw the original error. I'm not sure what benefit wrapping the error in another error provides, but it seems like throwing the original error would be more useful.
The reason why throw a generic Failed to fetch
is to be compliant with how the native fetch handles request errors. We value that compliance a lot because the way your test behaves with and without the mock must be close to identical. Without the mock, a request error will always result in a generic Failed to fetch
error. This is just how the Fetch API behaves, and we should respect that.
Not to mention, any custom properties on the thrown error aren't accessible on the wrapped error. That means the nice output that assertion errors typically create in the console are lost.
Just like the native fetch, we preserve the actual error thrown in the error.cause
property. Your assertion errors will be visible there.
If you must wrap the original error, at least append the original error message after "Failed to fetch", so we can see "Failed to fetch: My original error message".
This changes the type of the error and deviates the fetch behavior compared to when you aren't using Interceptors. I don't believe this is the way forward.
How we can improve this
I agree that's a suboptimal developer experience. On our end, I think to improve the developer experience, we can forward the original error to the console alongside the actual generic error:
console.error(originalError)
throw new TypeError('Failed to fetch', { cause: originalError })
However, we cannot reliably reason about which errors you wish to see and which you don't. If you are mocking intentional server-side errors, you don't want to see those repeated in your console during the test run. This makes it hard for us to differentiate between these two errors, and this is the reason why I don't think we should do anything about them implicitly.
How you can improve this
On your end, you shouldn't put assertions in request handlers. Remember that you write request handlers from the server's perspective. This means that any error thrown in a handler is treated as an error thrown in the actual server processing your request. Naturally, it translates to the network.
Instead, capture the resolver call and assert on the mock:
const resolverListener = vi.fn()
server.use(http.get(url, resolverListener))
await waitFor(() => expect(resolverListener).toHaveBeenCalled())
expect(resolverListener).toHaveBeenCalledWith(
expect.objectContaining({
params: { folder_id: expectedFolderId },
// ...other assertions.
})
)
To assert more complex structures, using asymmetric assertions can be tedious. Instead, you can unwrap the call to the mock function and assert on the data itself:
const { params, request } = resolverListener.mock.calls[0][0]
// ...assertions.
This is how I recommend solving this problem:
- Don't mix network behavior and the test logic.
- Write assertions independently of their source (the mock function).
from interceptors.
On your end, you shouldn't put assertions in request handlers.
Ah, this makes sense, thanks for explaining.
The reason why throw a generic Failed to fetch is to be compliant with how the native fetch handles request errors.
I understand what you are saying in theory, but perhaps my view on what's happening is different. My understanding is that "failed to fetch" occurs in standard fetch()
when the request can't be completed from the browser, which basically happens in a small number of circumstances:
- Incorrect URL format
- Invalid method
- Invalid headers
- Incorrect CORS response
- No response received
With the first three, this occurs because of validation before the network request is made, while the fourth occurs basically says "you're not allowed to make this request", and the fifth means the server disappeared. None of these situations seems to be relevant to the case where an interceptor has an error during execution.
Remember that you write request handlers from the server's perspective. This means that any error thrown in a handler is treated as an error thrown in the actual server processing your request.
And this is where I'm confused. From the server's perspective, an error while processing a route would most likely not crash the server (no response sent, so "failed to fetch"), but rather result in a 500 error being sent back to the client. And if I was writing actual server logic and there was a crash, I would expect that error to be the one I received, not "failed to fetch", which is a client-side error.
My expectation for MSW was that either of those two behaviors would occur when there's an error in an interceptor if the intent is to write interceptors as if they're the server.
from interceptors.
I think what you are saying makes sense. MSW by itself coerces these errors to 500 responses in the browser but I realized now that we don't do that for the Node.js counterpart. I think that's an oversight and we should fix it.
I propose this:
- If you respond with
Response.error()
, it translates to the genericFailed to fetch
because it stands for the network error. - If your request handler (request listener in the context of Interceptors) throws an exception, it gets coerced to a 500 response with the error message details in the response body. Quite the same as we do right here: https://github.com/mswjs/msw/blob/fc44a2c83250f9fd4d6e5c9c7ef73fcb657127fe/src/browser/setupWorker/start/createRequestListener.ts#L119-L133
This will actually create a more consistent behavior between environments.
from interceptors.
@nzakas, thanks for pointing out this inconsistency! It was always the intention to coerce unhandled exceptions to 500 server errors. Somehow, the Interceptors didn't implement that.
I've opened a PR to fix this behavior. Unhandled exceptions will now result in 500 error responses, and to mock a request (network) error, one can use request.respondWith(Response.error())
just like before.
from interceptors.
Since this is a breaking change, I will schedule it for the next minor version release. I may need to publish a few bugfixes around WebSockets until then.
from interceptors.
Related Issues (20)
- should call callback before response event HOT 2
- ClientRequest: doesn't throw error when writing after end on mock responses
- Handle http.request() with no options HOT 1
- Replace "uuid" with "crypto.randomUUID()" HOT 3
- Suppress errors after request handler HOT 1
- ReadableStream cannot be properly polyfilled in this engine HOT 5
- Error using BatchInterceptor with browserInterceptors in browser environment. HOT 7
- `Response.type` throws in miniflare-like environments HOT 1
- Support "CONNECT" requests (in proxies) HOT 11
- Support HTTP2 HOT 3
- Intercepted fetch results in the the process never exiting / hangs Mocha tests
- error listener get called twice on mocked error with sync handler HOT 2
- Use "urlToHttpOptions" from "node:url"
- Header keys for requests are being converted to lowercase
- ReferenceError: TextEncoder is not defined when running (jest) tests HOT 4
- XMLHttpRequestController creates bad URL when location exists but href not set HOT 4
- Support aborting intercepted requests HOT 6
- WebSocket: Outgoing client events have the wrong "currentTarget" HOT 2
- WebSocket: Decide how to handle actual server errors
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from interceptors.