2
0

mock-fetch.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Mocking the global.fetch and global.Headers
  2. global.fetch = jest.fn();
  3. global.Headers = jest.fn();
  4. // Helper to mock a success JSON response.
  5. fetch.mockResponseSuccessJSON = (body) => {
  6. fetch.mockImplementationOnce(() =>
  7. Promise.resolve({
  8. json: () => Promise.resolve(JSON.parse(body)),
  9. ok: true,
  10. status: 200,
  11. statusText: 'OK',
  12. }),
  13. );
  14. };
  15. // Helper to mock a success text response.
  16. fetch.mockResponseSuccessText = (body) => {
  17. fetch.mockImplementationOnce(() =>
  18. Promise.resolve({
  19. text: () => Promise.resolve(body),
  20. ok: true,
  21. status: 200,
  22. statusText: 'OK',
  23. }),
  24. );
  25. };
  26. // Helper to mock a failure response.
  27. fetch.mockResponseFailure = () => {
  28. fetch.mockImplementationOnce(() =>
  29. Promise.resolve({
  30. status: 500,
  31. statusText: 'Internal Error',
  32. }),
  33. );
  34. };
  35. fetch.mockResponseCrash = () => {
  36. fetch.mockImplementationOnce(() =>
  37. // eslint-disable-next-line prefer-promise-reject-errors
  38. Promise.reject({
  39. status: 500,
  40. statusText: 'Internal Error',
  41. }),
  42. );
  43. };
  44. // Helper to mock a timeout response.
  45. fetch.mockResponseTimeout = () => {
  46. fetch.mockImplementationOnce(() => {
  47. const timeout = 1000;
  48. return new Promise((resolve) => {
  49. setTimeout(() => setTimeout(resolve, timeout), timeout);
  50. });
  51. });
  52. };