mock-fetch.js 935 B

1234567891011121314151617181920212223242526272829303132333435363738
  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(() => Promise.resolve({
  7. json: () => Promise.resolve(JSON.parse(body)),
  8. status: 200,
  9. statusText: 'OK',
  10. }));
  11. };
  12. // Helper to mock a failure response.
  13. fetch.mockResponseFailure = () => {
  14. fetch.mockImplementationOnce(() => Promise.resolve({
  15. status: 500,
  16. statusText: 'Internal Error',
  17. }));
  18. };
  19. fetch.mockResponseCrash = () => {
  20. fetch.mockImplementationOnce(() => Promise.reject({
  21. status: 500,
  22. statusText: 'Internal Error',
  23. }));
  24. };
  25. // Helper to mock a timeout response.
  26. fetch.mockResponseTimeout = () => {
  27. fetch.mockImplementationOnce(() => {
  28. const timeout = 1000;
  29. return new Promise((resolve) => {
  30. setTimeout(() => setTimeout(resolve, timeout), timeout);
  31. });
  32. });
  33. };