api.tsx 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import isEqual from 'lodash/isEqual';
  2. import * as ApiNamespace from 'sentry/api';
  3. const RealApi: typeof ApiNamespace = jest.requireActual('sentry/api');
  4. export class Request {}
  5. export const initApiClientErrorHandling = RealApi.initApiClientErrorHandling;
  6. export const hasProjectBeenRenamed = RealApi.hasProjectBeenRenamed;
  7. const respond = (isAsync: boolean, fn?: Function, ...args: any[]): void => {
  8. if (!fn) {
  9. return;
  10. }
  11. if (isAsync) {
  12. setTimeout(() => fn(...args), 1);
  13. return;
  14. }
  15. fn(...args);
  16. };
  17. type FunctionCallback<Args extends any[] = any[]> = (...args: Args) => void;
  18. /**
  19. * Callables for matching requests based on arbitrary conditions.
  20. */
  21. interface MatchCallable {
  22. (url: string, options: ApiNamespace.RequestOptions): boolean;
  23. }
  24. type ResponseType = ApiNamespace.ResponseMeta & {
  25. body: any;
  26. callCount: 0;
  27. headers: Record<string, string>;
  28. match: MatchCallable[];
  29. method: string;
  30. statusCode: number;
  31. url: string;
  32. };
  33. type MockResponse = [resp: ResponseType, mock: jest.Mock];
  34. /**
  35. * Compare two records. `want` is all the entries we want to have the same value in `check`
  36. */
  37. function compareRecord(want: Record<string, any>, check: Record<string, any>): boolean {
  38. for (const entry of Object.entries(want)) {
  39. const [key, value] = entry;
  40. if (!isEqual(check[key], value)) {
  41. return false;
  42. }
  43. }
  44. return true;
  45. }
  46. afterEach(() => {
  47. // if any errors are caught we console.error them
  48. const errors = Object.values(Client.errors);
  49. if (errors.length > 0) {
  50. for (const err of errors) {
  51. // eslint-disable-next-line no-console
  52. console.error(err);
  53. }
  54. Client.errors = {};
  55. }
  56. });
  57. class Client implements ApiNamespace.Client {
  58. static mockResponses: MockResponse[] = [];
  59. static mockAsync = false;
  60. static clearMockResponses() {
  61. Client.mockResponses = [];
  62. }
  63. /**
  64. * Create a query string match callable.
  65. *
  66. * Only keys/values defined in `query` are checked.
  67. */
  68. static matchQuery(query: Record<string, any>): MatchCallable {
  69. const queryMatcher: MatchCallable = (_url, options) => {
  70. return compareRecord(query, options.query ?? {});
  71. };
  72. return queryMatcher;
  73. }
  74. /**
  75. * Create a data match callable.
  76. *
  77. * Only keys/values defined in `data` are checked.
  78. */
  79. static matchData(data: Record<string, any>): MatchCallable {
  80. const dataMatcher: MatchCallable = (_url, options) => {
  81. return compareRecord(data, options.data ?? {});
  82. };
  83. return dataMatcher;
  84. }
  85. // Returns a jest mock that represents Client.request calls
  86. static addMockResponse(response: Partial<ResponseType>) {
  87. const mock = jest.fn();
  88. Client.mockResponses.unshift([
  89. {
  90. url: '',
  91. status: 200,
  92. statusCode: 200,
  93. statusText: 'OK',
  94. responseText: '',
  95. responseJSON: '',
  96. body: '',
  97. method: 'GET',
  98. callCount: 0,
  99. match: [],
  100. ...response,
  101. headers: response.headers ?? {},
  102. getResponseHeader: (key: string) => response.headers?.[key] ?? null,
  103. rawResponse: {
  104. headers: new Headers(),
  105. ok: true,
  106. redirected: false,
  107. status: 200,
  108. statusText: 'OK',
  109. url: 'http://localhost',
  110. bodyUsed: false,
  111. body: {
  112. locked: false,
  113. cancel: jest.fn(),
  114. getReader: jest.fn(),
  115. pipeThrough: jest.fn(),
  116. pipeTo: jest.fn(),
  117. tee: jest.fn(),
  118. },
  119. blob: jest.fn(),
  120. arrayBuffer: jest.fn(),
  121. json: jest.fn(),
  122. text: jest.fn(),
  123. formData: jest.fn(),
  124. clone: jest.fn(),
  125. type: 'basic',
  126. },
  127. },
  128. mock,
  129. ]);
  130. return mock;
  131. }
  132. static findMockResponse(url: string, options: Readonly<ApiNamespace.RequestOptions>) {
  133. return Client.mockResponses.find(([response]) => {
  134. if (url !== response.url) {
  135. return false;
  136. }
  137. if ((options.method || 'GET') !== response.method) {
  138. return false;
  139. }
  140. return response.match.every(matcher => matcher(url, options));
  141. });
  142. }
  143. activeRequests: Record<string, ApiNamespace.Request> = {};
  144. baseUrl = '';
  145. uniqueId() {
  146. return '123';
  147. }
  148. /**
  149. * In the real client, this clears in-flight responses. It's NOT
  150. * clearMockResponses. You probably don't want to call this from a test.
  151. */
  152. clear() {}
  153. wrapCallback<T extends any[]>(
  154. _id: string,
  155. func: FunctionCallback<T> | undefined,
  156. _cleanup: boolean = false
  157. ) {
  158. return (...args: T) => {
  159. // @ts-expect-error
  160. if (RealApi.hasProjectBeenRenamed(...args)) {
  161. return;
  162. }
  163. respond(Client.mockAsync, func, ...args);
  164. };
  165. }
  166. requestPromise(
  167. path: string,
  168. {
  169. includeAllArgs,
  170. ...options
  171. }: {includeAllArgs?: boolean} & Readonly<ApiNamespace.RequestOptions> = {}
  172. ): any {
  173. return new Promise((resolve, reject) => {
  174. this.request(path, {
  175. ...options,
  176. success: (data, ...args) => {
  177. includeAllArgs ? resolve([data, ...args]) : resolve(data);
  178. },
  179. error: (error, ..._args) => {
  180. reject(error);
  181. },
  182. });
  183. });
  184. }
  185. static errors: Record<string, Error> = {};
  186. // XXX(ts): We type the return type for requestPromise and request as `any`. Typically these woul
  187. request(url: string, options: Readonly<ApiNamespace.RequestOptions> = {}): any {
  188. const [response, mock] = Client.findMockResponse(url, options) || [
  189. undefined,
  190. undefined,
  191. ];
  192. if (!response || !mock) {
  193. const methodAndUrl = `${options.method || 'GET'} ${url}`;
  194. // Endpoints need to be mocked
  195. const err = new Error(`No mocked response found for request: ${methodAndUrl}`);
  196. // Mutate stack to drop frames since test file so that we know where in the test
  197. // this needs to be mocked
  198. const lines = err.stack?.split('\n');
  199. const startIndex = lines?.findIndex(line => line.includes('.spec.'));
  200. err.stack = ['\n', lines?.[0], ...(lines?.slice(startIndex) ?? [])].join('\n');
  201. // Throwing an error here does not do what we want it to do....
  202. // Because we are mocking an API client, we generally catch errors to show
  203. // user-friendly error messages, this means in tests this error gets gobbled
  204. // up and developer frustration ensues.
  205. // We track the errors on a static member and warn afterEach test.
  206. Client.errors[methodAndUrl] = err;
  207. } else {
  208. // has mocked response
  209. // mock gets returned when we add a mock response, will represent calls to api.request
  210. mock(url, options);
  211. const body =
  212. typeof response.body === 'function' ? response.body(url, options) : response.body;
  213. if (![200, 202].includes(response.statusCode)) {
  214. response.callCount++;
  215. const errorResponse = Object.assign(
  216. {
  217. status: response.statusCode,
  218. responseText: JSON.stringify(body),
  219. responseJSON: body,
  220. },
  221. {
  222. overrideMimeType: () => {},
  223. abort: () => {},
  224. then: () => {},
  225. error: () => {},
  226. },
  227. new XMLHttpRequest()
  228. );
  229. this.handleRequestError(
  230. {
  231. id: '1234',
  232. path: url,
  233. requestOptions: options,
  234. },
  235. errorResponse as any,
  236. 'error',
  237. 'error'
  238. );
  239. } else {
  240. response.callCount++;
  241. respond(
  242. Client.mockAsync,
  243. options.success,
  244. body,
  245. {},
  246. {
  247. getResponseHeader: (key: string) => response.headers[key],
  248. statusCode: response.statusCode,
  249. status: response.statusCode,
  250. }
  251. );
  252. }
  253. }
  254. respond(Client.mockAsync, options.complete);
  255. }
  256. handleRequestError = RealApi.Client.prototype.handleRequestError;
  257. }
  258. export {Client};