handleXhrErrorResponse.spec.jsx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import * as Sentry from '@sentry/react';
  2. import {handleXhrErrorResponse} from 'sentry/utils/handleXhrErrorResponse';
  3. import RequestError from 'sentry/utils/requestError/requestError';
  4. describe('handleXhrErrorResponse', function () {
  5. const stringError = {responseJSON: {detail: 'Error'}, status: 400};
  6. const objError = {
  7. status: 400,
  8. responseJSON: {detail: {code: 'api-err-code', message: 'Error message'}},
  9. };
  10. beforeEach(function () {
  11. jest.clearAllMocks();
  12. });
  13. it('does nothing if we have invalid response', function () {
  14. handleXhrErrorResponse('', null);
  15. expect(Sentry.captureException).not.toHaveBeenCalled();
  16. handleXhrErrorResponse('', undefined);
  17. expect(Sentry.captureException).not.toHaveBeenCalled();
  18. });
  19. it('captures an exception to sdk when `resp.detail` is a string', function () {
  20. handleXhrErrorResponse('String error', stringError);
  21. expect(Sentry.captureException).toHaveBeenCalledWith(new Error('String error'));
  22. });
  23. it('captures an exception to sdk when `resp.detail` is an object', function () {
  24. handleXhrErrorResponse('Object error', objError);
  25. expect(Sentry.captureException).toHaveBeenCalledWith(new Error('Object error'));
  26. });
  27. it('ignores `sudo-required` errors', function () {
  28. handleXhrErrorResponse('Sudo required error', {
  29. status: 401,
  30. responseJSON: {
  31. detail: {
  32. code: 'sudo-required',
  33. detail: 'Sudo required',
  34. },
  35. },
  36. });
  37. expect(Sentry.captureException).not.toHaveBeenCalled();
  38. });
  39. it('adds data to the scope', () => {
  40. const status = 404;
  41. const responseJSON = {
  42. detail: {
  43. code: 'distracted-by-squirrel',
  44. detail: 'Got distracted by a squirrel',
  45. },
  46. };
  47. const err = new RequestError('GET', '/ball', new Error('API error'), {
  48. status,
  49. responseJSON,
  50. });
  51. const mockScope = new Sentry.Scope();
  52. const setExtrasSpy = jest.spyOn(mockScope, 'setExtras');
  53. const setTagsSpy = jest.spyOn(mockScope, 'setTags');
  54. const hub = Sentry.getCurrentHub();
  55. jest.spyOn(hub, 'pushScope').mockReturnValueOnce(mockScope);
  56. handleXhrErrorResponse("Can't fetch ball", err);
  57. expect(setExtrasSpy).toHaveBeenCalledWith({status, responseJSON});
  58. expect(setTagsSpy).toHaveBeenCalledWith({
  59. responseStatus: status,
  60. endpoint: 'GET /ball',
  61. });
  62. });
  63. });