ky
ky copied to clipboard
ky.get().json() throws, while ky.get().then(r => r.json()) does not in jest tests
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",
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()
);
}
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.