request.test.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import { initial, isInitialized, request, requestPagination } from "./request";
  2. const fetchSuccess = jest.fn(() =>
  3. Promise.resolve({
  4. ok: true,
  5. json: () => Promise.resolve({ data: "test", success: true }),
  6. headers: new Map(),
  7. })
  8. );
  9. // 原样返回
  10. const fetchEcho = jest.fn((url: string, options: RequestInit) => {
  11. return Promise.resolve({
  12. ok: true,
  13. json: () =>
  14. Promise.resolve({
  15. data: JSON.parse(options.body as string),
  16. success: true,
  17. }),
  18. headers: new Map(),
  19. });
  20. });
  21. afterEach(() => {
  22. fetchSuccess.mockClear();
  23. fetchEcho.mockClear();
  24. });
  25. test("initial", async () => {
  26. expect(request("test")).rejects.toThrow("请先调用 initial 初始化");
  27. initial({
  28. baseURL: "https://example.com",
  29. fetch: (() => {}) as any,
  30. });
  31. expect(isInitialized).toBeTruthy();
  32. });
  33. test("request", async () => {
  34. const fetch = fetchSuccess;
  35. initial({
  36. baseURL: "https://example.com",
  37. fetch: fetch as any,
  38. });
  39. expect(
  40. await request(
  41. "/test",
  42. { foo: "bar" },
  43. {
  44. method: "PUT",
  45. searchParams: { one: "two" },
  46. headers: {
  47. "X-POWER-BY": "test",
  48. },
  49. }
  50. )
  51. ).toEqual("test");
  52. expect(fetch).toBeCalledWith("https://example.com/test?one=two", {
  53. body: '{"foo":"bar"}',
  54. headers: {
  55. "content-type": "application/json;charset=UTF-8",
  56. "x-power-by": "test",
  57. },
  58. method: "PUT",
  59. mode: "cors",
  60. });
  61. });
  62. test("name 参数变量替换", async () => {
  63. const fetch = fetchSuccess;
  64. initial({
  65. baseURL: "https://example.com",
  66. fetch: fetch as any,
  67. });
  68. request("/test/{id}/{foo.bar}", { id: "123", foo: { bar: "baz" } });
  69. expect(fetch).toBeCalledWith("https://example.com/test/123/baz", {
  70. body: '{"id":"123","foo":{"bar":"baz"}}',
  71. headers: { "content-type": "application/json;charset=UTF-8" },
  72. method: "POST",
  73. mode: "cors",
  74. });
  75. });
  76. test("支持识别 application/x-www-form-urlencoded", async () => {
  77. const fetch = fetchSuccess;
  78. initial({
  79. baseURL: "https://example.com",
  80. fetch: fetch as any,
  81. });
  82. expect(
  83. await request(
  84. "/test",
  85. { foo: "bar", baz: 1 },
  86. {
  87. method: "POST",
  88. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  89. }
  90. )
  91. ).toEqual("test");
  92. expect(fetch).toBeCalledWith("https://example.com/test", {
  93. body: "baz=1&foo=bar",
  94. headers: { "content-type": "application/x-www-form-urlencoded" },
  95. method: "POST",
  96. mode: "cors",
  97. });
  98. });
  99. test("拦截器", async () => {
  100. const fetch = fetchSuccess;
  101. initial({
  102. baseURL: "https://example.com",
  103. fetch: fetch as any,
  104. interceptor: async (req, next) => {
  105. req.headers["X-POWER-BY"] = "test";
  106. req.searchParams.one = "two";
  107. req.method = "GET";
  108. req.body.foo = "foo";
  109. const response = await next();
  110. response.data = "boom";
  111. return response;
  112. },
  113. });
  114. expect(await request("/test", { bar: "bar" })).toEqual("boom");
  115. expect(fetch).toBeCalledWith(
  116. "https://example.com/test?bar=bar&foo=foo&one=two",
  117. {
  118. body: undefined,
  119. headers: {
  120. "content-type": "application/json;charset=UTF-8",
  121. "x-power-by": "test",
  122. },
  123. method: "GET",
  124. mode: "cors",
  125. }
  126. );
  127. });
  128. test("拦截器元数据", async () => {
  129. const fetch = fetchSuccess;
  130. const interceptor = jest.fn((req, next) => {
  131. return next();
  132. });
  133. initial({
  134. baseURL: "https://example.com",
  135. fetch: fetch as any,
  136. interceptor,
  137. });
  138. // @ts-expect-error
  139. request("/test", {}, { meta: { foo: "bar" } });
  140. expect(interceptor.mock.calls[0][0]).toEqual({
  141. body: {},
  142. headers: { "content-type": "application/json;charset=UTF-8" },
  143. // 拦截到元数据
  144. meta: { foo: "bar" },
  145. method: "POST",
  146. name: "/test",
  147. searchParams: {},
  148. });
  149. expect(fetch).toBeCalledWith("https://example.com/test", {
  150. body: "{}",
  151. headers: { "content-type": "application/json;charset=UTF-8" },
  152. method: "POST",
  153. mode: "cors",
  154. });
  155. });
  156. test("拦截重试, 用于重新登录等复杂场景", async () => {
  157. const fetch = fetchEcho;
  158. initial({
  159. baseURL: "https://example.com",
  160. fetch: fetch as any,
  161. interceptor: async (req, next) => {
  162. req.body.time = 1;
  163. await next();
  164. // 二次重试请求
  165. req.body.time = 2;
  166. return await next();
  167. },
  168. });
  169. const result = await request("/test");
  170. // 返回最后一次 next 的请求
  171. expect(result).toEqual({ time: 2 });
  172. // fetch 被调用两次
  173. expect(fetch).toBeCalledWith("https://example.com/test", {
  174. body: '{"time":1}',
  175. headers: { "content-type": "application/json;charset=UTF-8" },
  176. method: "POST",
  177. mode: "cors",
  178. });
  179. expect(fetch).toBeCalledWith("https://example.com/test", {
  180. body: '{"time":2}',
  181. headers: { "content-type": "application/json;charset=UTF-8" },
  182. method: "POST",
  183. mode: "cors",
  184. });
  185. });
  186. test("拦截重试,调用 next 多次应该抛出异常", async () => {
  187. const fetch = fetchSuccess;
  188. initial({
  189. baseURL: "https://example.com",
  190. fetch: fetch as any,
  191. interceptor: async (req, next) => {
  192. while (true) {
  193. await next();
  194. }
  195. },
  196. });
  197. await expect(request("/test")).rejects.toThrow(
  198. "拦截器调用 next 次数过多, 请检查代码,可能存在无限循环"
  199. );
  200. expect(fetch).toBeCalledTimes(3);
  201. });
  202. test("响应内容规范化 - error", async () => {
  203. const fetch = jest.fn(() =>
  204. Promise.resolve({
  205. ok: true,
  206. json: () =>
  207. Promise.resolve({
  208. data: "test",
  209. success: false,
  210. errorCode: 400,
  211. errorMessage: "mock error",
  212. }),
  213. headers: new Map(),
  214. })
  215. );
  216. initial({
  217. baseURL: "https://example.com",
  218. fetch: fetch as any,
  219. });
  220. try {
  221. await request("/test");
  222. // never
  223. expect(true).toBe(false);
  224. } catch (err) {
  225. expect(err).toMatchObject({ code: 400, message: "mock error" });
  226. }
  227. });
  228. test("响应内容规范化 - success", async () => {
  229. const fetch = jest.fn(() =>
  230. Promise.resolve({
  231. ok: true,
  232. json: () =>
  233. Promise.resolve({
  234. data: "test",
  235. success: true,
  236. code: 400,
  237. msg: "mock error",
  238. other: "foo",
  239. }),
  240. headers: new Map(),
  241. })
  242. );
  243. initial({
  244. baseURL: "https://example.com",
  245. fetch: fetch as any,
  246. });
  247. expect(await requestPagination("/test")).toEqual({
  248. __raw__: {
  249. data: {
  250. code: 400,
  251. data: "test",
  252. msg: "mock error",
  253. other: "foo",
  254. success: true,
  255. },
  256. header: {},
  257. statusCode: undefined,
  258. },
  259. data: "test",
  260. code: 400,
  261. msg: "mock error",
  262. other: "foo",
  263. success: true,
  264. });
  265. });
  266. test("变量替换", async () => {
  267. const fetch = fetchSuccess;
  268. initial({
  269. baseURL: "https://example.com",
  270. fetch: fetch as any,
  271. globalVariables: { appId: "mock" },
  272. });
  273. expect(
  274. await request(
  275. "/test",
  276. { foo: "bar", myId: "{appId}" },
  277. {
  278. method: "PUT",
  279. searchParams: { one: "two", myId: "{appId}" },
  280. headers: {
  281. "X-POWER-BY": "test",
  282. "MY-ID": "{appId}",
  283. },
  284. }
  285. )
  286. ).toEqual("test");
  287. expect(fetch).toBeCalledWith("https://example.com/test?myId=mock&one=two", {
  288. body: '{"foo":"bar","myId":"mock"}',
  289. headers: {
  290. "content-type": "application/json;charset=UTF-8",
  291. "x-power-by": "test",
  292. "my-id": "mock",
  293. },
  294. method: "PUT",
  295. mode: "cors",
  296. });
  297. });