Jest Vue Ожидаемая фиктивная функция была вызвана, но не вызвана - PullRequest
0 голосов
/ 08 февраля 2019

Я пытаюсь смоделировать вызов API, используя Jest и Vue, но я получаю сообщение об ошибке "Ожидаемая фиктивная функция была вызвана с: ... но не вызывается"

Я попытался найти решениено еще ничего не нашел.

import DocumentService from "../../src/services/document";
import mockedData from "../__mockData__/documents";
import axios from "axios";

it("should call Document Service and  download a document", () => {
  let catchFn = jest.fn(),
    thenFn = jest.fn();

  DocumentService.downloadDocumentById(jwtToken, DocumentURL, id)
    .then(thenFn)
    .then(catchFn);

  // expect(axios.get).toHaveBeenCalledWith(DocumentURL + "/" + id + "/content", {
  //     headers: { Authorization: "Bearer " + jwtToken, "X-role": "SuperUser" }
  // });

  expect(axios.get).toHaveBeenCalledWith(DocumentURL);

  let responseObj = { data: mockedData };
  axios.get.Mockresponse(responseObj);
  expect(thenFn).toHaveBeenCalledWith(mockedData);
  expect(catchFn).not.toHaveBeenCalled();
});

1 Ответ

0 голосов
/ 09 февраля 2019

Тест выполняется синхронно, и expect запускается и завершается неудачей, прежде чем обратные вызовы Promise имеют шанс на выполнение.

Убедитесь, что вы await Promise вернули DocumentService.downloadDocumentById, чтобы датьу обратных вызовов есть шанс запустить:

it("should call Document Service and  download a document", async () => {  // use an async test function
  let catchFn = jest.fn(),
    thenFn = jest.fn();

  const promise = DocumentService.downloadDocumentById(jwtToken, DocumentURL, id)
    .then(thenFn)
    .then(catchFn);  // remember the Promise

  expect(axios.get).toHaveBeenCalledWith(DocumentURL);

  let responseObj = { data: mockedData };
  axios.get.Mockresponse(responseObj);
  await promise;  // wait for the Promise
  expect(thenFn).toHaveBeenCalledWith(mockedData);  // SUCCESS
  expect(catchFn).not.toHaveBeenCalled();  // SUCCESS
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...