I try to mock a fetch call using fetch-mock
and jest. My fetch call is a POST request with request body and two headers.
My code looks like this:
let payload = JSON.stringify({"some" : "value"});
let headers = new Headers({"Accept": "application/json", "Content-Type": "application/json"});
let options = {method: "POST", body: payload, headers: headers};
fetch('http://someUrl', options)
.then(response => response.json())
.then(data => {this.data = data})
.catch(e => {console.log("exception", e)});
I tried the following in my test:
let fetchMock = require('fetch-mock');
let response = {
status: 200,
body: {data : "1234"}
};
let payload = JSON.stringify({"some" : "value"});
let headers = new Headers({"Accept": "application/json", "Content-Type": "application/json"});
let options = {"method": "POST", "body": payload, "headers": headers};
fetchMock.mock('http://someUrl', response, options);
But it gives me this error:
Unmatched POST to http://someUrl
Any help/hints appreciated!
I solved this by not using new Headers
.
let payload = JSON.stringify({"some" : "value"});
let headers = {"Accept": "application/json", "Content-Type":
"application/json"};
let options = {method: "POST", body: payload, headers: headers};
fetch('http://someUrl', options)
.then(response => response.json())
.then(data => {this.data = data})
.catch(e => {console.log("exception", e)});
let headers = {"Accept": "application/json", "Content-Type":
"application/json"};
let options = {method: "POST", headers: headers, body: payload};
fetchMock.mock('http://someUrl', response, options);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With