Closed markdon closed 1 year ago
Hey, @markdon. Thanks for reporting this.
We are working on improving how request bodies are read, and this use case is going to the list of things we need to account for. Meanwhile, you can still use req.body
if that used to work previously. The logic there should remain the same.
Actually, I only spent the time investigating this after req.body.toString()
started throwing a very similar error :( Just accessing req.body
at all throws the same error.
I can refactor the few of my tests this affected to move to latest msw.
xhr:request POST /login middleware function threw an exception! TypeError: The "input" argument must be an instance of ArrayBuffer or ArrayBufferView. Received an instance of URLSearchParams at new NodeError (node:internal/errors:371:5) at TextDecoder.decode (node:internal/encoding:413:15) at decodeBuffer (/Users/mark/projects/cra-msw/node_modules/@mswjs/interceptors/src/utils/bufferUtils.ts:11:18) at RestRequest.body (/Users/mark/projects/cra-msw/node_modules/msw/src/utils/request/MockedRequest.ts:111:18) at /Users/mark/projects/cra-msw/src/setupTests.ts:8:44 at /Users/mark/projects/cra-msw/node_modules/msw/src/handlers/RequestHandler.ts:232:55 at RestHandler.run (/Users/mark/projects/cra-msw/node_modules/msw/src/handlers/RequestHandler.ts:215:34) at /Users/mark/projects/cra-msw/node_modules/msw/src/utils/getResponse.ts:50:34 at processTicksAndRejections (node:internal/process/task_queues:96:5) at getResponse (/Users/mark/projects/cra-msw/node_modules/msw/src/utils/getResponse.ts:41:18) { code: 'ERR_INVALID_ARG_TYPE' } +12ms
Oh, so the reason is not to read the body but to construct it. He'd have to support that.
We're using something called IsomorphicRequest
abstract that allows us to handle different request body types in the same manner. That abstraction only accepts ArrayBuffer
as request body (which we want to keep) but the consumer (MSW in this case) can transform the body however they need to eventually provide the buffer.
So, I'd imagine this support to be:
URLSearchParams
.ArrayBuffer
.Contributions are welcome!
Sounds pretty straight forward to implement! I would love to contribute, if I hadn't just signed up to a project with a tight timeline for the next few months.
I will check back later!
My workaround, which was actually for FormData
, is the following:
jest.spyOn(global, "FormData").mockImplementation(mockFormDataForMSW);
jest.mock("util", mockNodeUtilForMSW);
function mockFormDataForMSW() {
return new FormDataFakeArrayBuffer(0) as unknown as FormData;
}
function mockNodeUtilForMSW() {
const real = jest.requireActual("util") as typeof import("util");
return {
...real,
TextDecoder: class extends real.TextDecoder {
decode(
input?: NodeJS.ArrayBufferView | ArrayBuffer | null,
options?: { stream?: boolean | undefined },
): string {
if (input instanceof FormDataFakeArrayBuffer) return input.toString();
return super.decode(input, options);
}
},
};
}
class FormDataFakeArrayBuffer extends ArrayBuffer {
private params = new URLSearchParams();
append(param: string, value: string) {
return this.params.append(param, value);
}
toString() {
return this.params.toString();
}
}
For reference/SEO, the error was:
The input argument must be an instance of ArrayBuffer or ArrayBufferView. Received an instance of FormData
or
The input argument must be an instance of ArrayBuffer or ArrayBufferView. Received an instance of URLSearchParams
I'm not sure why I didn't consider this before but surely the easiest workaround (for URLSearchParams) is to create the request with a string instead of URLSearchParams object. e.g. use URLSearchParams.toString()
for the body when calling fetch.
The MSW handler will always need to parse the text body with new URLSearchParams(await body.text())
as there is no Request
method that gets the body as a URLSearchParams object.
Same issue as mine in #1327 but with FormData
bodies. msw
just plain broke reading request bodies in v0.44.0.
New features keep getting added in the 0.x line so that it's totally OK to break stuff from a semver perspective. And bugs are not fixed.
Same problem here.
I used Axios instead of Fetch and it works !
@ddolcimascolo, a true sadness is having a 7M/week downloaded library used by FAANG and having to develop it over weekends instead of spending time with one's family (which I've promised myself not to do anymore, thus you will have issues that I don't have time/desire to work on). But hey, you can take a step towards resolving that sadness, here you go.
This is going to be fixed by #1436 so I'm not going to do any work around this until that API lands. If you're blocked by this, consider contributing, I'd do my best to review your code and release it.
Yeah. My message above was itself sad, sorry about that, probably written while closing yet another upgrade merge request on MSW that I can't merge because of this blocker. You do a great job in maintaining OSS projects, keep up the great work!
Since my message above I've contributed a fix, even though you implemented #1436 in the end which is a really nice addition.
Cheers, David
I will check back later!
It looks like a lot of progress has been made towards the Fetch API update that replaces the related code and fixes this issue. There's a beta available to try.
I had a quick look at making a fix for the current release of msw but @mswjs/interceptors has already moved on from the related IsomorphicRequest class and the Fetch API update looks pretty close to done anyway.
Hey, just little question from me. I am using latest msw, node and react-query@^3.39.2. And I am trying to connect with a Keycloak (newest stable version) for fresh token before running tests. I have to use URLSearchParams formatting in body to construct fetch and I am getting this mentioned error from msw:
"The "input" argument must be an instance of ArrayBuffer or ArrayBufferView. Received an instance of URLSearchParams."
I guess, #1436 is fixing it also for this case, right? Otherwise what is the status of completition @kettanaito ?
@DusanPausly, correct. The current version of MSW doesn't support URLSearchParams
as the request body. The Fetch API feature will add that support.
This has been released in v2.0.0!
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.
Prerequisites
Environment check
msw
versionNode.js version
v16.13.0
Reproduction repository
https://github.com/markdon/cra-msw
Reproduction steps
clone repo
npm i
DEBUG=* npm run test -- --watchAll=false
Current behavior
I think this is related to https://github.com/mswjs/msw/issues/1318
When handling a fetch request where the request body is a URLSearchParameters object, the body can not be read in the handler. This was previously available through
request.body
(v0.27.1).request.body
is now deprecated.I would expect to be able to just use the newer
request.text()
, however this seems to throw an error parsing the body.Debug logs. See ERR_INVALID_ARG_TYPE
Expected behavior
A request body of type URLSearchParameters should be able to be read in a handler. I suggest via
request.text()
, which would return the value of URLSearchParameters.toString().