mswjs / msw

Industry standard API mocking for JavaScript.
https://mswjs.io
MIT License
16k stars 522 forks source link

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

Closed lavoscore closed 6 months ago

lavoscore commented 7 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 6 months 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 5 months 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.