Open phil294 opened 4 years ago
+1, found myself wishing for this today.
It's a bit complex, but I've worked around this by defining a custom jest matcher
expect.extend({
toBeOk(response: Response) {
if (response.ok) {
return {
message: () => 'Ok',
pass: true,
};
} else {
return {
message: () => {
const request = response.request;
// Format the request and response as CURL output for debugging.
return [
`> ${request.method} ${request.url} HTTP/1.1`,
formatHeaders('> ', request.headers),
`< HTTP/1.1 ${response.status}`,
formatHeaders('< ', response.headers),
response.text,
]
.filter(Boolean)
.join('\n');
},
pass: false,
};
}
},
});
function formatHeaders(
prefix: string,
headers: Response['headers'] | Response['request']['headers'] | undefined | null,
) {
if (!headers) return undefined;
const entries =
headers instanceof Headers ? Array.from(headers.entries()) : Object.entries(headers);
entries.map(([key, value]) => `${prefix}${key}: ${value}`).join('\n');
}
and corresponding jest.d.ts
declare global {
namespace jest {
interface Matchers<R> {
toBeOk(): R;
}
}
}
export {};
It can be used as
expect(response).toBeOk();
Since #95 got closed 6 years ago and there seems to be no incentive to reopen this, here's an almost 1:1 copy of that issue, but instead of reporting the hard coded
.error
property, imo the entire response body should be printed out, as currently the server response is disregarded completely.