Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mock fetch request with fetch-mock using headers

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!

like image 222
Ria Avatar asked Apr 06 '17 14:04

Ria


1 Answers

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);
like image 97
Ria Avatar answered Oct 28 '22 17:10

Ria