ReferenceError: fetch is not defined – Postman

Total
1
Shares

In Postman, I run an arbitrary request. I put the following code in either the
Pre-req. script or in the Tests script:

fetch('https://jsonplaceholder.typicode.com/todos/3')
  .then(response => response.text())
  .then(responseBody => {
    console.log('The response body:');
    console.log(responseBody);
  });

When I hit the Send button to run the request, I get ReferenceError: fetch
is not defined
:

ReferenceError: fetch is not defined

When searching online, I have hardly found anything about this error message
in Postman.
Now, Postman is not a web browser in the normal sense, but just about every
well known web browser offers the Fetch API
these days.

Does Postman not implement the Fetch API?


Solution

Does Postman not implement the Fetch API?

I think not. The closest correspondence to the fetch() command
is pm.sendRequest().
But pm.sendRequest returns a pm object and not a Promise,
at least for now.

I have found a workaround, though.
In the code snippet below I define the pmFetch() function which is meant to
do what the fetch() command does in a normal web browser.

pmFetch('https://jsonplaceholder.typicode.com/todos/3')
  .then(response => response.json())
  .then(responseBody => {
    console.log('The response body:');
    console.log(responseBody);
    console.log('responseBody.title: "' + responseBody.title + '"');
  });
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //
function pmFetch (url) {
  return new Promise ((resolve, reject) => {
    pm.sendRequest(url, function (err, response) {
      if (err) reject(err);
      resolve(response);
    });
  });
}

pmFetch mimics the Fetch API

Here is a link to the Postman Collection
in case you want to download, import, and run the collection.

Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *