request-with-memo.spec.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
  3. * SPDX-License-Identifier: MIT
  4. */
  5. import { vi, describe, test, expect } from 'vitest';
  6. import { clearRequestCache, requestWithMemo } from './request-with-memo';
  7. function delay(time: number): Promise<void> {
  8. return new Promise(res => {
  9. setTimeout(res, time);
  10. });
  11. }
  12. describe('request with memo', () => {
  13. test('base', async () => {
  14. const cb = vi.fn();
  15. const requestMock = async () => cb();
  16. const newRequest = requestWithMemo(requestMock);
  17. await newRequest();
  18. await newRequest();
  19. expect(cb.mock.calls.length).toEqual(1);
  20. clearRequestCache();
  21. await newRequest();
  22. expect(cb.mock.calls.length).toEqual(2);
  23. });
  24. test('timeout clear', async () => {
  25. const cb = vi.fn();
  26. const requestMock = async () => cb();
  27. const newRequest = requestWithMemo(requestMock, 0);
  28. await newRequest();
  29. await delay(10);
  30. await newRequest();
  31. expect(cb.mock.calls.length).toEqual(2);
  32. });
  33. test('request with error', async () => {
  34. const cb = vi.fn();
  35. const requestMock = async () => {
  36. cb();
  37. throw new Error('requestError');
  38. };
  39. const newRequest = requestWithMemo(requestMock, 0);
  40. let errorTimes = 0;
  41. try {
  42. await newRequest();
  43. } catch (e) {
  44. errorTimes += 1;
  45. }
  46. try {
  47. await newRequest();
  48. } catch (e) {
  49. errorTimes += 1;
  50. }
  51. expect(errorTimes).toEqual(2);
  52. // 错误发生不会被缓存
  53. expect(cb.mock.calls.length).toEqual(2);
  54. });
  55. });