【问题标题】:Jest Vue Expected mock function to have been called with, but not calledJest Vue 预期的模拟函数已被调用,但未调用
【发布时间】:2019-07-03 03:09:53
【问题描述】:

我正在尝试使用 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();
});

【问题讨论】:

    标签: vue.js jestjs axios


    【解决方案1】:

    测试同步运行,expect 运行并在 Promise 回调有机会运行之前失败。

    确保 awaitDocumentService.downloadDocumentById 返回的 Promise 给回调一个运行的机会:

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

    【讨论】:

      【解决方案2】:

      遇到了同样的问题,就这样搞定了:

      1. import axios from 'axios';
      2. 测试中axios.get = jest.fn();
      3. expect( axios.get ).toBeCalledWith( yourUrl );

      【讨论】:

        猜你喜欢
        • 2019-03-28
        • 2018-12-27
        • 2019-07-21
        • 1970-01-01
        • 2018-05-25
        • 2019-10-27
        • 1970-01-01
        • 1970-01-01
        • 2019-03-23
        相关资源
        最近更新 更多