msw: Always receiving TypeError: Network request failed

Describe the bug

In my jest tests, if I call server.listen() all of my network requests inside of the test fail with the generic fetch error TypeError: Network request failed. These requests succeed if I don’t attempt to run msw at all.

The failure occurs for EVERY request, regardless of whether or not msw has a handler that matches the request or not.

My test looks something like this:

import { setupServer } from "msw/node";
import { rest } from "msw";

const handlers = [
  // behavior is the same regardless of whether or not I have any handlers defined
];

const server = setupServer(handlers);
describe("Some Thing", () => {
  beforeAll(() => server.listen());
  afterEach(() => server.resetHandlers());
  afterAll(() => server.close());

  test('example test', () => {
    await fetch(
      "https://api.fake.com/something/i/know/works",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ foo: "bar" }),
      }
    );
  })
}

I am adding react-testing-library tests (using msw on the recommendation of KCD) to an older react application. The app was created with CRA ~3.5 years ago. I’ve updated react-scripts to a more recent version just in case this was the cause, but I’ve had no luck.

I think it’s likely that either my configuration is wrong, or that I have a dependency problem, but the error from fetch is so opaque that I’m finding myself stuck. I don’t know if there are any debug tools available to inspect or trace the path of this these failing requests to find out where they’re getting jammed up.

Environment

My react application sits in a yarn workspace monorepo, but when I isolate the app from its “siblings” and just do npm i && npm test I see the same behavior.

  • msw: 0.21.2
  • nodejs: 10.18.1 & nodejs: 12.16.3
  • npm: 6.14.4
  • yarn: 1.22.4
  • react-scripts: 3.2.0 which installs jest: 24.9.0
  • I run my tests with jest-environment-jsdom-sixteen: 1.0.3

To Reproduce

I’m not yet sure how to reproduce. I’m not even sure if this is a real bug. I think it’s most likely a misconfiguration on my part or a weird dependency issue.

Expected behavior

I expect that network requests are either handled by msw handlers or are passed through to be handled by the network.

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 6
  • Comments: 25 (11 by maintainers)

Commits related to this issue

Most upvoted comments

Awesome! Thanks for the link! I hadn’t found my way to the debugging page yet. Running with the debug output on led me to solve my problem immediately, and now I know!

2021-03-04T18:54:47.370Z XHR POST http://localhost:9000/redemptions middleware function threw an exception! TypeError: Object.fromEntries is not a function

I was working in a shell that had node 10 installed by default. I updated to node 14, which is the version I want to be running anyway, and tests pass no problem! Thanks!

Hey, @spruce-bruce. No worries, let’s figure it out together.

The first thing I’d recommend is to enable the onUnhandledRequest option. The library will warn/error you if your test makes a request that you don’t have described in your request handlers. That’s exactly the situation you’re experiencing.

Replace your beforeAll hook with this:

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));

We’ve got a few other recommendations to try out if this one doesn’t help in the Debugging uncaught requests recipe. Please read through it.

I’m suspecting a hard-coded localhost:9000 to be the culprit.

I know the library but sometime I make the same mistake hahahaha. I think that also other people can have this kind of problem, maybe we can add a check on setupServer and setupWoker functions. What do you think?

Perhaps let’s check if the given handlers are not an Array? Throw an error in that case.

I had the same problem. I put the return of the handler in a try and in catch I got the actual error. it said (res) is not a function! when I looked more carefully I found out that I’ve called the rest.get function like below : rest.get(“url”, (res, req, ctx) => { return res( …

which is wrong because I didnt follow the right order of res and req!

alright lets continue on #971

Would you be interested in opening a pull request?

well, let’s experiment it 😃

I had the same issue.TypeError: Network request is extremely hard to understand. It took me quite a bit of time to debug, as well. I also noticed that you’d get this error when you have an undefined variable in your request handler. More specific error messages would be welcomed.

Hi @spruce-bruce what do you think of this check? This can be added also on setupServer function

diff --git a/src/setupWorker/setupWorker.ts b/src/setupWorker/setupWorker.ts
index 7e4caf3..9f490cd 100644
--- a/src/setupWorker/setupWorker.ts
+++ b/src/setupWorker/setupWorker.ts
@@ -42,6 +42,14 @@ let listeners: Listener[] = []
 export function setupWorker(
   ...requestHandlers: RequestHandlersList
 ): SetupWorkerApi {
+  requestHandlers.forEach((handler) => {
+    if (typeof handler !== 'object' || !('parse' in handler))
+      throw new Error(
+        `[MSW] The handlers passed to setupWorker function are not of the right type.
+          A common mistake is to call setupWorker in this way setupWorker(requestHandlers),
+          you should instead call it as setupWorker(...requestHandlers)`,
+      )
+  })
   const context: SetupWorkerInternalContext = {
     worker: null,
     registration: null,

Hi @spruce-bruce thanks for raising this 😄

You should call setupServer in this way setupServer(...handlers). Let me know if this will solve your issue.

Thanks