api.tsx 8.3 KB

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