api.tsx 8.5 KB

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