Jest Vue已调用但未调用的预期模拟函数

时间:2019-02-08 20:34:04

标签: vue.js jestjs axios

我正在尝试使用Jest和Vue模拟api调用,但出现错误“预期的模拟函数已被调用为:...但未调用”

我试图找到解决方案,但还没有找到任何东西。

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 个答案:

答案 0 :(得分:0)

测试将同步运行,并且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
});

答案 1 :(得分:0)

遇到同样的麻烦,就是这样:

  1. import axios from 'axios';
  2. 正在测试axios.get = jest.fn();
  3. expect( axios.get ).toBeCalledWith( yourUrl );
相关问题