Jest Vue 预期的模拟函数已被调用,但未调用
Posted
技术标签:
【中文标题】Jest Vue 预期的模拟函数已被调用,但未调用【英文标题】:Jest Vue Expected mock function to have been called with, but not called 【发布时间】: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();
);
【问题讨论】:
【参考方案1】:测试同步运行,expect
运行并在 Promise
回调有机会运行之前失败。
确保 await
和 DocumentService.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】:遇到了同样的问题,就这样搞定了:
import axios from 'axios';
测试中axios.get = jest.fn();
expect( axios.get ).toBeCalledWith( yourUrl );
【讨论】:
以上是关于Jest Vue 预期的模拟函数已被调用,但未调用的主要内容,如果未能解决你的问题,请参考以下文章