jest js test multipul api ответы по одному и не ждите, пока все не закончится - PullRequest
1 голос
/ 02 апреля 2020

Я пытаюсь проверить свою логику c с помощью Jest для загрузки нескольких файлов. У меня есть список идентификаторов файлов для каждого файла. Я go извлекаю большой двоичный объект с помощью вызова ajax, якорь (ссылка) добавляется после получения ответа от API, затем щелчок запускается и удаляется без промедления. это вызовет загрузку. Лог загрузки c работает должным образом, поскольку один файл выбирается и загружается, другой файл выбирается и загружается.

Если я запускаю эту логику c с одним загружаемым файлом, он может найти элемент 'downloadFileLink'. если я запускаю больше одного файла, он не может найти элемент.

похоже, что первое ожидание ожидает завершения всех вызовов. (Если я напечатаю значение secondedCountCalls в первом ожидании, это 1 должно быть 0). Как проверить каждый вызов перед тем, как будет выполнен другой?

// after each fetch this is the download logic that is called
const downloadFile = (downloadMeta, downloadLink) => {
  const a = document.createElement("a");
  a.href = downloadLink;
  a.target = "_parent";
  a.download = downloadMeta.fileMeta?._id;
  a.setAttribute("data-testid", "downloadFileLink");
  a.style.display = "none";
  (document.body || document.documentElement).appendChild(a);
  a.click();
  setTimeout(() => {
    a!.parentNode!.removeChild(a);
  }, 0);
};

   let firstCountCalls = 0,
      secondImgCheckbox = 0;

   // mocking the API call of the first file
   mock.get(
      /files\/media\/exams\/3b650f70-d8a6-4135-8570-6d2510869930\/files\/45ddf63a-32e0-4a89-8bd5-ffe843cc63f3/i,
      once((req, res) => {
        firstCountCalls += 1;
        spyReq = req;
        return res.status(200).body(new Blob([""], { type: "image/jpeg" }));
      })
    );

    // mocking the API call of the second file
    mock.get(
      /files\/media\/exams\/3b650f70-d8a6-4135-8570-6d2510869930\/files\/45d8f63a-32e0-4a89-8bd5-ffe843cc63f4/i,
      once((req, res) => {
        seconedCountCalls += 1;
        spyReq = req;
        return res.status(200).body(new Blob([""], { type: "image/jpeg" }));
      })
    );

    // trigger start download 
    const downloadButton = comp.getByTestId("download-imgs-button");
    expect(downloadButton).not.toBeDisabled();
    fireEvent.click(downloadButton);
    expect(downloadButton).toBeDisabled();
    // waiting for first fetch of blob from API
    await wait(() => {
      expect(firstCountCalls).toBe(1);
      const downloadImageLink = comp.getByTestId( <-------- falls here can't find the item
        "downloadFileLink"
      ) as HTMLAnchorElement;
      expect(downloadImageLink.download).toEqual(
        "45ddf63a-32e0-4a89-8bd5-ffe843cc63f3"
      );
    });

    // waiting for second fetch of blob from API
    await wait(() => {
      expect(secondImgCheckbox).toBe(1);
      const downloadImageLink = comp.getByTestId(
        "downloadFileLink"
      ) as HTMLAnchorElement;
      expect(downloadImageLink.download).toEqual(
        "45ddf63a-32e0-4a89-8bd5-ffe843cc63f3"
      );
    });

Заранее спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...