mock-fetch.js 1.0 KB

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