test: refactor mocks to use spyOn for better isolation

This commit is contained in:
syntaxbullet
2025-12-19 13:31:14 +01:00
parent 4e228bb7a3
commit 1f7679e5a1
4 changed files with 62 additions and 72 deletions

View File

@@ -1,6 +1,8 @@
import { describe, it, expect, mock, beforeEach, setSystemTime } from "bun:test";
import { describe, it, expect, mock, beforeEach, afterEach, spyOn } from "bun:test";
import { TradeService } from "./trade.service";
import { itemTransactions } from "@/db/schema";
import { economyService } from "@/modules/economy/economy.service";
import { inventoryService } from "@/modules/inventory/inventory.service";
// Mock dependencies
const mockInsert = mock();
@@ -22,38 +24,34 @@ mock.module("@/lib/DrizzleClient", () => {
};
});
// Mock External Services
const mockModifyUserBalance = mock();
mock.module("@/modules/economy/economy.service", () => ({
economyService: {
modifyUserBalance: mockModifyUserBalance
}
}));
const mockAddItem = mock();
const mockRemoveItem = mock();
mock.module("@/modules/inventory/inventory.service", () => ({
inventoryService: {
addItem: mockAddItem,
removeItem: mockRemoveItem
}
}));
describe("TradeService", () => {
const userA = { id: "1", username: "UserA" };
const userB = { id: "2", username: "UserB" };
let mockModifyUserBalance: any;
let mockAddItem: any;
let mockRemoveItem: any;
beforeEach(() => {
mockModifyUserBalance.mockClear();
mockAddItem.mockClear();
mockRemoveItem.mockClear();
mockInsert.mockClear();
mockValues.mockClear();
// Clear sessions
(TradeService as any).sessions.clear();
// Spies
mockModifyUserBalance = spyOn(economyService, 'modifyUserBalance').mockResolvedValue({} as any);
mockAddItem = spyOn(inventoryService, 'addItem').mockResolvedValue({} as any);
mockRemoveItem = spyOn(inventoryService, 'removeItem').mockResolvedValue({} as any);
});
afterEach(() => {
mockModifyUserBalance.mockRestore();
mockAddItem.mockRestore();
mockRemoveItem.mockRestore();
});
describe("createSession", () => {
it("should create a new session", () => {
const session = TradeService.createSession("thread1", userA, userB);
@@ -108,7 +106,7 @@ describe("TradeService", () => {
TradeService.addItem("thread1", "1", { id: 10, name: "Sword" }, 2n);
const session = TradeService.getSession("thread1");
expect(session?.userA.offer.items[0].quantity).toBe(3n);
expect(session?.userA.offer.items[0]!.quantity).toBe(3n);
});
});