I have tests which use fetch-mock
to mock a post request with parameters in the body.
I can mock the request but i cannot find a way to return a response according to the request's body.
Lets say i have a post request with :
const body = {flag : true} // can be either true or false
const configInit: RequestInit = {
method: "POST",
credentials: "include",
body: JSON.stringify(body)
};
fetch(REQUEST_URL, configInit)
Currently my mock looks like this:
//.. some definithion of responseA and responseB
fetchMock.post(
REQUEST_URL,
(url, opts) => opts && opts.body && opts.body.flag ? responseA : responseB ,
{ overwriteRoutes: true }
);
But it says that opts.body is a 'BodyInit' object and does not have property "flag".
I have found the docomentation but i couldn't find anywhere the right way of doing this.
How can i get the parameters from the request to my mock response?
Is this way the best practice? maybe i should separate the requests using a FunctionMatcher
(which doesn't work for me either)?
I'm not sure of best pattern or anything but my quick solution is just to call the toString() method that BodyInit provides so for example:
fetchMock.get('someUrl', (_, opts) => {
const body = JSON.parse(opts.body.toString())
})
Sorry for the incomplete answer just enough to hopefully get you on your way