mswjs / msw

Seamless REST/GraphQL API mocking library for browser and Node.js.
https://mswjs.io
MIT License
15.28k stars 479 forks source link

Calls to worker.use() remove handlers to same endpoint with different method #2129

Closed lavoscore closed 1 month ago

lavoscore commented 2 months ago

I'm trying to write dynamic handler builders, but I'm hitting this issue:

worker.use(
  http.get("/v1/issues", () => HttpResponse.json(/* some json */))
)

// this will make the get handler ignored!
worker.use(
  http.post("/v1/issues", () => HttpResponse.json(/* some json */))
);

I'm aware that repeated calls to worker.use prepend handlers to the existing context, and therefore order matters. But then why does this code work?

// both handlers work
worker.use(
  http.get("/v1/issues", () => HttpResponse.json(/* some json */)),
  http.post("/v1/issues", () => HttpResponse.json(/* some json */))
);

Since both handlers work when added in a single worker.use call, shouldn't this method take into account any methods previously added to the context so as not to remove them and provide the same end result?

kettanaito commented 1 month ago

Hi, @lavoscore. Thanks for reporting this.

There's no difference between these two snippets:

worker.use(a)
worker.use(b)
worker.use(a, b)

It's prepending values to an array:

https://github.com/mswjs/msw/blob/7cf34c15ddd2edc688dc848eaf6eb89883ac6df6/src/core/SetupApi.ts#L26-L28

I've added regression tests for your use case and they are passing for worker.use() and server.use():

https://github.com/mswjs/msw/pull/2145

Could you please take a look at those tests and see if you can spot any difference compared to what you are doing? If the issue still persists for you, please provide a reproduction repository where I can see it. Thanks.

kettanaito commented 1 month ago

Released: v2.3.1 🎉

This has been released in v2.3.1!

Make sure to always update to the latest version (npm i msw@latest) to get the newest features and bug fixes.


Predictable release automation by @ossjs/release.