import { requestWithPercent } from "./request";

describe("requestWithPercent", () => {
  const mockFetch = jest.fn();

  beforeAll(() => {
    mockFetch.mockResolvedValue({
      headers: {
        get: () => "100",
      },
      body: {
        getReader: jest.fn().mockReturnValue({
          read: jest
            .fn()
            .mockResolvedValueOnce({
              done: false,
              value: new Uint8Array([1, 2, 3]),
            })
            .mockResolvedValueOnce({
              done: false,
              value: new Uint8Array([4, 5, 6]),
            })
            .mockResolvedValueOnce({ done: true }),
        }),
      },
    });

    global.fetch = mockFetch;
  });

  afterAll(() => {
    // @ts-ignore
    delete global.fetch;
    mockFetch.mockRestore();
  });

  test("数据返回 ArrayBuffer", async () => {
    const onProcessMock = jest.fn();

    const result = await requestWithPercent({
      url: "https://example.com/data",
      onProcess: onProcessMock,
    });

    expect(onProcessMock).toHaveBeenCalledTimes(2);
    expect(result).toBeInstanceOf(Uint8Array);
    expect(result.length).toBe(6);
    expect(result).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6]));
  });
});
