我正在尝试使用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();
});
答案 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)
遇到同样的麻烦,就是这样:
import axios from 'axios';
axios.get = jest.fn();
expect( axios.get ).toBeCalledWith( yourUrl );