我一直在嘗試模擬fetchLiveMatches匯入的函式,但沒有成功。我一直在瀏覽一些想法,但我想我已經用完了,所以我可以使用一些幫助。關于我做錯了什么的任何想法?
live.test.js
import * as liveController from "./live";
import { jest } from "@jest/globals";
import * as liveService from "../service/live";
import { buildReq, buildRes, buildNext } from "../utils/testingHelper";
jest.mock("../service/live");
beforeEach(() => {
jest.clearAllMocks();
});
describe("Live Controller", () => {
test("calls fetchLiveMatches function to fetch from external API", async () => {
const req = buildReq();
const res = buildRes();
const next = buildNext();
await liveController.getLiveMatches(req, res, next);
expect(next).not.toHaveBeenCalled();
expect(liveService.fetchLiveMatches).toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(500);
expect(res.status).toHaveBeenCalledTimes(1);
});
});
服務/live.js
import axios from "axios";
async function fetchLiveMatches() {
// Some hidden code
return axios({
method: "get",
url: `${API_FOOTBALL_BASE_URL}${GET_EVENTS}${MATCH_LIVE}${WIDGET_KEY}${TIMEZONE}${DETAILS}`,
headers: {}
}).then(res => res.data);
}
export { fetchLiveMatches };
jest.config.js
export default {
testEnvironment: "jest-environment-node",
transform: {}
};
包.json
{
"name": "server",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"license": "MIT",
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"axios": "^1.1.3",
"eslint": "^8.26.0",
"jest": "^29.2.2",
"prettier": "^2.7.1"
},
"scripts": {
"start": "node --watch index.js",
"start:no-watch": "node index.js",
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch"
}
}
測驗錯誤輸出
Live Controller ? calls fetchLiveMatches function to fetch from external API
expect(received).toHaveBeenCalled()
Matcher error: received value must be a mock or spy function
Received has type: function
Received has value: [Function fetchLiveMatches]
uj5u.com熱心網友回復:
只需發布我為最終面臨相同問題的任何人找到的解決方案:
首先,由于我在沒有 Babel 的情況下使用 ES6/模塊匯入,因此我將模擬函式更改為unstable_mockModule,然后根據檔案,我決定在模擬模塊后嘗試在測驗范圍內動態匯入。
如果您使用 ES 模塊匯入,那么您通常傾向于將匯入陳述句放在測驗檔案的頂部。但通常你需要在模塊使用之前指示 Jest 使用模擬。出于這個原因,Jest 會自動將 jest.mock 呼叫提升到模塊的頂部(在任何匯入之前)。要了解有關此內容的更多資訊并查看它的實際效果,請參閱此 repo。
測驗組件使用以下代碼:
import { jest } from "@jest/globals";
import { buildReq, buildRes, buildNext } from "../utils/testingHelper";
describe("Live Controller", () => {
test("calls fetchLiveMatches function to fetch from external API", async () => {
jest.unstable_mockModule("../service/live", () => ({
fetchLiveMatches: jest.fn(() => [])
}));
const { getLiveMatches } = await import("./live");
const { fetchLiveMatches } = await import("../service/live");
const req = buildReq();
const res = buildRes();
const next = buildNext(msg => console.log(msg));
await getLiveMatches(req, res, next);
expect(fetchLiveMatches).toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(200);
expect(res.status).toHaveBeenCalledTimes(1);
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/524138.html
上一篇:傳播物件并添加標志node.js
下一篇:構造3個關系的新物件
