2
votes

I am trying to mock an api call using Jest and Vue but I get the error "Expected mock function to have been called with: ... but not called"

I have tried to find a solution but haven't found anything yet.

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();
});
2

2 Answers

0
votes

The test runs synchronously and the expect runs and fails before the Promise callbacks have a chance to run.

Make sure you await the Promise returned by DocumentService.downloadDocumentById to give the callbacks a chance to run:

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
});
0
votes

Had the same trouble, made it this way:

  1. import axios from 'axios';
  2. in test axios.get = jest.fn();
  3. expect( axios.get ).toBeCalledWith( yourUrl );