ky icon indicating copy to clipboard operation
ky copied to clipboard

ky.get().json() throws, while ky.get().then(r => r.json()) does not in jest tests

Open kosciolek opened this issue 3 years ago • 2 comments

I've got a CRA app that's using ky and is tested via Jest.

I've added to package.json the following to avoid the ESM error while testing, as advised in another issue:

  "jest": {
    "transformIgnorePatterns": [
      "/node_modules/(?!(ky))"
    ]
  }

Now, given this code:

  function runLongForm() {
    ky
      .get("https://api.exchangerate.host/latest")
      .then((r) => {
        console.log('no shortcut status', r.status);
        return r.json();
      })
      .then((data) => console.log("no shortcut", data));
  }

  async function runShortForm() {
    console.log(
      "json shortcut",
      await ky.get("https://api.exchangerate.host/latest").json()
    );
  }

In the first case, the JSON response is logged, as expected.

In the second case, an exception is thrown (parsing error), and once .json() is changed to .text(), it can be seen that the reponse is just an empty string.

With other URLs the same happens.

Minimal reproduction repo (CRA) Code link

"ky": "^0.28.5",

kosciolek avatar Aug 16 '21 13:08 kosciolek

I ran into a similar issue, but it's actually a mistake in the example.

ky.get returns a Promise, calling .json() on a promise throws an error.

The following would work:

async function runShortForm() {
    console.log(
      "json shortcut",
      await (await ky.get("https://api.exchangerate.host/latest")).json()
    );
  }

enekesabel avatar Mar 31 '23 13:03 enekesabel

Calling .json() on the promise returned by Ky without awaiting it is the correct usage. We add this method to the promise, it's not a normal promise. Just makes the API a bit more convenient to use.

sholladay avatar Jul 27 '23 05:07 sholladay