0
0
mirror of https://github.com/sp-tarkov/server.git synced 2025-02-13 06:10:44 -05:00

Formatting for test classes.

This commit is contained in:
Refringe 2023-11-10 17:21:20 -05:00
parent 3ef51e771b
commit 320c8b7d48
No known key found for this signature in database
GPG Key ID: 64E03E5F892C6F9E
16 changed files with 1765 additions and 1749 deletions

View File

@ -9,8 +9,7 @@
"EditorConfig.EditorConfig", "EditorConfig.EditorConfig",
"dprint.dprint", "dprint.dprint",
"dbaeumer.vscode-eslint", "dbaeumer.vscode-eslint",
"biomejs.biome", "biomejs.biome"
"streetsidesoftware.code-spell-checker"
] ]
}, },
"settings": { "settings": {
@ -18,68 +17,7 @@
"editor.formatOnSave": true, "editor.formatOnSave": true,
"editor.defaultFormatter": "dprint.dprint", "editor.defaultFormatter": "dprint.dprint",
"editor.codeActionsOnSave": [ "editor.codeActionsOnSave": [
"source.fixAll.eslint",
"source.organizeImports.biome" "source.organizeImports.biome"
],
"cSpell.language": "en-GB",
"cSpell.words": [
"armor",
"asonline",
"behaviour",
"biomejs",
"botreload",
"currexp",
"currlvl",
"dbaeumer",
"deathmatch",
"dprint",
"edgeofdarkness",
"fulfill",
"gethideout",
"gifter",
"hpresource",
"inraid",
"isvalid",
"leftbehind",
"leveled",
"loadout",
"maxlvl",
"medkit",
"MEDSTATION",
"nextlvl",
"offraid",
"peacefullzryachiyevent",
"preparetoescape",
"prevexp",
"profileid",
"Protobuf",
"pscav",
"Ragfair",
"Regen",
"requestid",
"sanitise",
"Sanitised",
"scav",
"scavcase",
"scavs",
"Spawnpoint",
"spawnpoints",
"sptbear",
"sptdeveloper",
"spteasystart",
"sptusec",
"sptzerotohero",
"stackcount",
"statustimer",
"Tarkov",
"toggleable",
"tooshort",
"Ubgl",
"unrestartable",
"usec",
"userbuilds",
"weapongen",
"Wishlist"
] ]
} }
} }

View File

@ -1,20 +1,17 @@
import "reflect-metadata"; import "reflect-metadata";
import { container, DependencyContainer, Lifecycle } from "tsyringe"; import { container, DependencyContainer, Lifecycle } from "tsyringe";
// For the Vitest Custom Environment.
import type { Environment } from "vitest";
import { Container } from "@spt-aki/di/Container"; import { Container } from "@spt-aki/di/Container";
// Required for importing the database.
import path from "node:path";
import { IDatabaseTables } from "@spt-aki/models/spt/server/IDatabaseTables"; import { IDatabaseTables } from "@spt-aki/models/spt/server/IDatabaseTables";
import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer";
import { ImporterUtil } from "@spt-aki/utils/ImporterUtil"; import { ImporterUtil } from "@spt-aki/utils/ImporterUtil";
import path from "node:path";
import type { Environment } from "vitest";
// Manually mock for the logger. // Manually mock the logger.
import { WinstonLogger } from "@tests/__mocks__/WinstonLogger.mock"; import { WinstonLogger } from "@tests/__mocks__/WinstonLogger.mock";
export default <Environment> { export default <Environment>{
name: "spt-aki-server", name: "spt-aki-server",
transformMode: "ssr", transformMode: "ssr",
async setup() async setup()
@ -24,16 +21,16 @@ export default <Environment> {
Container.registerListTypes(container); Container.registerListTypes(container);
// Override registration to the container. // Override registration to the container.
container.register<WinstonLogger>("WinstonLogger", WinstonLogger, { lifecycle: Lifecycle.Singleton }); container.register<WinstonLogger>("WinstonLogger", WinstonLogger, {lifecycle: Lifecycle.Singleton});
// Import the database. // Import the database.
await importDatabase(container); await importDatabase(container);
return { return {
async teardown() async teardown()
{} {},
}; };
} },
}; };
/** /**

View File

@ -1,11 +1,12 @@
import "reflect-metadata"; import "reflect-metadata";
import { container } from "tsyringe"; import { container } from "tsyringe";
import { format } from "date-fns";
import { profileInsuranceFixture } from "@tests/__fixture__/profileInsurance.fixture";
import { Insurance } from "@spt-aki/models/eft/profile/IAkiProfile";
import { ItemHelper } from "@spt-aki/helpers/ItemHelper";
type DateInput = number | number[] | { [index: number]: number }; import { ItemHelper } from "@spt-aki/helpers/ItemHelper";
import { Insurance } from "@spt-aki/models/eft/profile/IAkiProfile";
import { profileInsuranceFixture } from "@tests/__fixture__/profileInsurance.fixture";
import { format } from "date-fns";
type DateInput = number | number[] | {[index: number]: number;};
export class ProfileInsuranceFactory export class ProfileInsuranceFactory
{ {
@ -61,7 +62,7 @@ export class ProfileInsuranceFactory
this.profileInsuranceFixture = this.profileInsuranceFixture.map((insurance) => this.profileInsuranceFixture = this.profileInsuranceFixture.map((insurance) =>
{ {
insurance.items = insurance.items.filter(item => !itemHelper.isAttachmentAttached(item)); insurance.items = insurance.items.filter((item) => !itemHelper.isAttachmentAttached(item));
return insurance; return insurance;
}); });
@ -78,8 +79,7 @@ export class ProfileInsuranceFactory
this.profileInsuranceFixture = this.profileInsuranceFixture.map((insurance) => this.profileInsuranceFixture = this.profileInsuranceFixture.map((insurance) =>
{ {
insurance.items = insurance.items.filter(item => itemHelper.isAttachmentAttached(item)); insurance.items = insurance.items.filter((item) => itemHelper.isAttachmentAttached(item));
return insurance; return insurance;
}); });

File diff suppressed because it is too large Load Diff

View File

@ -6,26 +6,30 @@ import { ILogger } from "@spt-aki/models/spt/utils/ILogger";
export class WinstonLogger implements ILogger export class WinstonLogger implements ILogger
{ {
writeToLogFile(data: string | Daum): void writeToLogFile(data: string | Daum): void
{ } {}
log(data: string | Record<string, unknown> | Error, color: string, backgroundColor?: string): void log(data: string | Record<string, unknown> | Error, color: string, backgroundColor?: string): void
{ } {}
logWithColor(data: string | Record<string, unknown>, textColor: LogTextColor, backgroundColor?: LogBackgroundColor): void logWithColor(
{ } data: string | Record<string, unknown>,
textColor: LogTextColor,
backgroundColor?: LogBackgroundColor,
): void
{}
error(data: string): void error(data: string): void
{ } {}
warning(data: string): void warning(data: string): void
{ } {}
success(data: string): void success(data: string): void
{ } {}
info(data: string): void info(data: string): void
{ } {}
debug(data: string| Record<string, unknown>, onlyShowInConsole?: boolean): void debug(data: string | Record<string, unknown>, onlyShowInConsole?: boolean): void
{ } {}
} }

View File

@ -1,16 +1,16 @@
/* eslint-disable @typescript-eslint/naming-convention */ /* eslint-disable @typescript-eslint/naming-convention */
import "reflect-metadata"; import "reflect-metadata";
import { container } from "tsyringe"; import { container } from "tsyringe";
import { vi, afterEach, describe, expect, it, beforeEach } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { InsuranceController } from "@spt-aki/controllers/InsuranceController"; import { InsuranceController } from "@spt-aki/controllers/InsuranceController";
import { ProfileInsuranceFactory } from "@tests/__factories__/ProfileInsurance.factory"; import { ProfileInsuranceFactory } from "@tests/__factories__/ProfileInsurance.factory";
import { MessageType } from "@spt-aki/models/enums/MessageType"; import { ItemHelper } from "@spt-aki/helpers/ItemHelper";
import { TraderHelper } from "@spt-aki/helpers/TraderHelper"; import { TraderHelper } from "@spt-aki/helpers/TraderHelper";
import { Item } from "@spt-aki/models/eft/common/tables/IItem"; import { Item } from "@spt-aki/models/eft/common/tables/IItem";
import { Insurance } from "@spt-aki/models/eft/profile/IAkiProfile"; import { Insurance } from "@spt-aki/models/eft/profile/IAkiProfile";
import { ItemHelper } from "@spt-aki/helpers/ItemHelper"; import { MessageType } from "@spt-aki/models/enums/MessageType";
describe("InsuranceController", () => describe("InsuranceController", () =>
{ {
@ -36,10 +36,12 @@ describe("InsuranceController", () =>
const session2 = "session2"; const session2 = "session2";
const profiles = { const profiles = {
[session1]: {}, [session1]: {},
[session2]: {} [session2]: {},
}; };
const getProfilesSpy = vi.spyOn(insuranceController.saveServer, "getProfiles").mockReturnValue(profiles); const getProfilesSpy = vi.spyOn(insuranceController.saveServer, "getProfiles").mockReturnValue(profiles);
const processReturnByProfileSpy = vi.spyOn(insuranceController, "processReturnByProfile").mockReturnValue(vi.fn()); const processReturnByProfileSpy = vi.spyOn(insuranceController, "processReturnByProfile").mockReturnValue(
vi.fn(),
);
// Execute the method. // Execute the method.
insuranceController.processReturn(); insuranceController.processReturn();
@ -55,7 +57,8 @@ describe("InsuranceController", () =>
it("should not attempt to process profiles if no profiles exist", () => it("should not attempt to process profiles if no profiles exist", () =>
{ {
const processReturnByProfileSpy = vi.spyOn(insuranceController, "processReturnByProfile").mockImplementation(vi.fn()); const processReturnByProfileSpy = vi.spyOn(insuranceController, "processReturnByProfile")
.mockImplementation(vi.fn());
// Execute the method. // Execute the method.
insuranceController.processReturn(); insuranceController.processReturn();
@ -119,7 +122,9 @@ describe("InsuranceController", () =>
// Verify that the correct methods were called. // Verify that the correct methods were called.
expect(mockGetProfile).toBeCalledTimes(1); expect(mockGetProfile).toBeCalledTimes(1);
expect(mockLoggerDebug).toBeCalledWith(`Found ${insuranceFixture.length} insurance packages in profile ${sessionID}`); expect(mockLoggerDebug).toBeCalledWith(
`Found ${insuranceFixture.length} insurance packages in profile ${sessionID}`,
);
expect(insuredFiltered.length).toBe(insuranceFixture.length); expect(insuredFiltered.length).toBe(insuranceFixture.length);
}); });
@ -141,7 +146,9 @@ describe("InsuranceController", () =>
// Verify that the correct methods were called. // Verify that the correct methods were called.
expect(mockGetProfile).toBeCalledTimes(1); expect(mockGetProfile).toBeCalledTimes(1);
expect(mockLoggerDebug).toBeCalledWith(`Found ${insuranceFixture.length} insurance packages in profile ${sessionID}`); expect(mockLoggerDebug).toBeCalledWith(
`Found ${insuranceFixture.length} insurance packages in profile ${sessionID}`,
);
expect(insuredFiltered.length).toBe(insuranceFixture.length - 1); // Should be 1 less than the original fixture. expect(insuredFiltered.length).toBe(insuranceFixture.length - 1); // Should be 1 less than the original fixture.
}); });
@ -157,11 +164,16 @@ describe("InsuranceController", () =>
// Execute the method, passing in a time that's two hours in the past. The function should use this past // Execute the method, passing in a time that's two hours in the past. The function should use this past
// date as the target to judge if an insurance package is ready to be sent or not. // date as the target to judge if an insurance package is ready to be sent or not.
const insuredFiltered = insuranceController.filterInsuredItems(sessionID, Math.floor((Date.now() / 1000) - (2 * 60 * 60))); const insuredFiltered = insuranceController.filterInsuredItems(
sessionID,
Math.floor((Date.now() / 1000) - (2 * 60 * 60)),
);
// Verify that the correct methods were called. // Verify that the correct methods were called.
expect(mockGetProfile).toBeCalledTimes(1); expect(mockGetProfile).toBeCalledTimes(1);
expect(mockLoggerDebug).toBeCalledWith(`Found ${insuranceFixture.length} insurance packages in profile ${sessionID}`); expect(mockLoggerDebug).toBeCalledWith(
`Found ${insuranceFixture.length} insurance packages in profile ${sessionID}`,
);
// Verify that the returned array is empty. // Verify that the returned array is empty.
expect(insuredFiltered.length).toBe(0); expect(insuredFiltered.length).toBe(0);
@ -186,7 +198,11 @@ describe("InsuranceController", () =>
insuranceController.processInsuredItems(insuranceFixture, sessionId); insuranceController.processInsuredItems(insuranceFixture, sessionId);
// Verify that the log was written. // Verify that the log was written.
expect(mockLoggerDebug).toBeCalledWith(`Processing ${insuranceFixture.length} insurance packages, which includes a total of ${insuranceController.countAllInsuranceItems(insuranceFixture)} items, in profile ${sessionId}`); expect(mockLoggerDebug).toBeCalledWith(
`Processing ${insuranceFixture.length} insurance packages, which includes a total of ${
insuranceController.countAllInsuranceItems(insuranceFixture)
} items, in profile ${sessionId}`,
);
}); });
it("should call processing methods once per insurance package", () => it("should call processing methods once per insurance package", () =>
@ -195,11 +211,19 @@ describe("InsuranceController", () =>
const packageCount = insuranceFixture.length; const packageCount = insuranceFixture.length;
// Spy on the processing methods. // Spy on the processing methods.
const mockFindItemsToDelete = vi.spyOn(insuranceController, "findItemsToDelete").mockImplementation(vi.fn()); const mockFindItemsToDelete = vi.spyOn(insuranceController, "findItemsToDelete").mockImplementation(
const mockRemoveItemsFromInsurance = vi.spyOn(insuranceController, "removeItemsFromInsurance").mockImplementation(vi.fn()); vi.fn(),
const mockAdoptOrphanedItems = vi.spyOn(insuranceController, "adoptOrphanedItems").mockImplementation(vi.fn()); );
const mockRemoveItemsFromInsurance = vi.spyOn(insuranceController, "removeItemsFromInsurance")
.mockImplementation(vi.fn());
const mockAdoptOrphanedItems = vi.spyOn(insuranceController, "adoptOrphanedItems").mockImplementation(
vi.fn(),
);
const mockSendMail = vi.spyOn(insuranceController, "sendMail").mockImplementation(vi.fn()); const mockSendMail = vi.spyOn(insuranceController, "sendMail").mockImplementation(vi.fn());
const mockRemoveInsurancePackageFromProfile = vi.spyOn(insuranceController, "removeInsurancePackageFromProfile").mockImplementation(vi.fn()); const mockRemoveInsurancePackageFromProfile = vi.spyOn(
insuranceController,
"removeInsurancePackageFromProfile",
).mockImplementation(vi.fn());
// Execute the method. // Execute the method.
insuranceController.processInsuredItems(insuranceFixture, sessionId); insuranceController.processInsuredItems(insuranceFixture, sessionId);
@ -219,22 +243,22 @@ describe("InsuranceController", () =>
{ {
const insurance = [ const insurance = [
{ {
"_id": "1", _id: "1",
"upd": 1234567890, upd: 1234567890,
"items": [ items: [
{ "_id": "1", "parentId": "1", "slotId": "1" }, {_id: "1", parentId: "1", slotId: "1"},
{ "_id": "2", "parentId": "1", "slotId": "2" } {_id: "2", parentId: "1", slotId: "2"},
] ],
}, },
{ {
"_id": "2", _id: "2",
"upd": 1234567890, upd: 1234567890,
"items": [ items: [
{ "_id": "3", "parentId": "2", "slotId": "1" }, {_id: "3", parentId: "2", slotId: "1"},
{ "_id": "4", "parentId": "2", "slotId": "2" }, {_id: "4", parentId: "2", slotId: "2"},
{ "_id": "5", "parentId": "2", "slotId": "3" } {_id: "5", parentId: "2", slotId: "3"},
] ],
} },
]; ];
const expectedCount = 5; // 2 items in the first package + 3 items in the second package. const expectedCount = 5; // 2 items in the first package + 3 items in the second package.
@ -261,15 +285,15 @@ describe("InsuranceController", () =>
{ {
const insurance = [ const insurance = [
{ {
"_id": "1", _id: "1",
"upd": 1234567890, upd: 1234567890,
"items": [] items: [],
}, },
{ {
"_id": "2", _id: "2",
"upd": 1234567890, upd: 1234567890,
"items": [] items: [],
} },
]; ];
const expectedCount = 0; const expectedCount = 0;
@ -289,7 +313,7 @@ describe("InsuranceController", () =>
const packageToRemove = { const packageToRemove = {
date: "01.11.2023", date: "01.11.2023",
time: "10:51", time: "10:51",
location: "factory4_day" location: "factory4_day",
}; };
const profile = { const profile = {
insurance: [ insurance: [
@ -298,20 +322,20 @@ describe("InsuranceController", () =>
systemData: { systemData: {
date: "01.11.2023", date: "01.11.2023",
time: "11:18", time: "11:18",
location: "factory4_day" location: "factory4_day",
} },
} },
}, },
{ // This one should be removed { // This one should be removed
messageContent: { messageContent: {
systemData: { systemData: {
date: "01.11.2023", date: "01.11.2023",
time: "10:51", time: "10:51",
location: "factory4_day" location: "factory4_day",
} },
} },
} },
] ],
}; };
// Mock the getProfile method to return the above profile. // Mock the getProfile method to return the above profile.
@ -325,7 +349,7 @@ describe("InsuranceController", () =>
expect(profile.insurance[0].messageContent.systemData).toStrictEqual({ expect(profile.insurance[0].messageContent.systemData).toStrictEqual({
date: "01.11.2023", date: "01.11.2023",
time: "11:18", time: "11:18",
location: "factory4_day" location: "factory4_day",
}); });
}); });
@ -335,7 +359,7 @@ describe("InsuranceController", () =>
const packageToRemove = { const packageToRemove = {
date: "01.11.2023", date: "01.11.2023",
time: "10:51", time: "10:51",
location: "factory4_day" location: "factory4_day",
}; };
const profile = { const profile = {
insurance: [ insurance: [
@ -344,11 +368,11 @@ describe("InsuranceController", () =>
systemData: { systemData: {
date: "01.11.2023", date: "01.11.2023",
time: "10:51", time: "10:51",
location: "factory4_day" location: "factory4_day",
} },
} },
} },
] ],
}; };
// Mock the getProfile method to return the above profile. // Mock the getProfile method to return the above profile.
@ -361,7 +385,9 @@ describe("InsuranceController", () =>
insuranceController.removeInsurancePackageFromProfile(sessionID, packageToRemove); insuranceController.removeInsurancePackageFromProfile(sessionID, packageToRemove);
// Verify that the log was written. // Verify that the log was written.
expect(mockLoggerDebug).toBeCalledWith(`Removed insurance package with date: ${packageToRemove.date}, time: ${packageToRemove.time}, and location: ${packageToRemove.location} from profile ${sessionID}. Remaining packages: ${profile.insurance.length}`); expect(mockLoggerDebug).toBeCalledWith(
`Removed insurance package with date: ${packageToRemove.date}, time: ${packageToRemove.time}, and location: ${packageToRemove.location} from profile ${sessionID}. Remaining packages: ${profile.insurance.length}`,
);
}); });
it("should not remove any packages if the specified package is not found", () => it("should not remove any packages if the specified package is not found", () =>
@ -370,7 +396,7 @@ describe("InsuranceController", () =>
const packageToRemove = { const packageToRemove = {
date: "01.11.2023", date: "01.11.2023",
time: "10:51", time: "10:51",
location: "factory4_day" location: "factory4_day",
}; };
const profile = { const profile = {
insurance: [ insurance: [
@ -379,11 +405,11 @@ describe("InsuranceController", () =>
systemData: { systemData: {
date: "02.11.2023", date: "02.11.2023",
time: "10:50", time: "10:50",
location: "factory4_night" location: "factory4_night",
} },
} },
} },
] ],
}; };
// Mock the getProfile method to return the above profile. // Mock the getProfile method to return the above profile.
@ -399,7 +425,6 @@ describe("InsuranceController", () =>
describe("findItemsToDelete", () => describe("findItemsToDelete", () =>
{ {
it("should handle an empty insurance package", () => it("should handle an empty insurance package", () =>
{ {
const insurancePackage = insuranceFixture[0]; const insurancePackage = insuranceFixture[0];
@ -423,12 +448,14 @@ describe("InsuranceController", () =>
const mockPopulateItemsMap = vi.spyOn(insuranceController, "populateItemsMap"); const mockPopulateItemsMap = vi.spyOn(insuranceController, "populateItemsMap");
const mockPopulateParentAttachmentsMap = vi.spyOn(insuranceController, "populateParentAttachmentsMap"); const mockPopulateParentAttachmentsMap = vi.spyOn(insuranceController, "populateParentAttachmentsMap");
const mockIsAttachmentAttached = vi.spyOn(insuranceController.itemHelper, "isAttachmentAttached"); const mockIsAttachmentAttached = vi.spyOn(insuranceController.itemHelper, "isAttachmentAttached");
const mockProcessAttachments = vi.spyOn(insuranceController, "processAttachments").mockImplementation(vi.fn()); const mockProcessAttachments = vi.spyOn(insuranceController, "processAttachments").mockImplementation(
vi.fn(),
);
// Add all items to the toDelete set. Not realistic, but it's fine for this test. // Add all items to the toDelete set. Not realistic, but it's fine for this test.
const mockProcessRegularItems = vi.fn((insured, toDelete) => const mockProcessRegularItems = vi.fn((insured, toDelete) =>
{ {
insured.items.forEach(item => toDelete.add(item._id)); insured.items.forEach((item) => toDelete.add(item._id));
}); });
vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems); vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems);
@ -444,7 +471,7 @@ describe("InsuranceController", () =>
// Verify that the result is correct. // Verify that the result is correct.
expect(result.size).toBe(numberOfItems); expect(result.size).toBe(numberOfItems);
expect(result).toEqual(new Set(insured.items.map(item => item._id))); expect(result).toEqual(new Set(insured.items.map((item) => item._id)));
}); });
it("should ignore orphaned attachments", () => it("should ignore orphaned attachments", () =>
@ -463,7 +490,9 @@ describe("InsuranceController", () =>
{ {
return new Map<string, Item[]>(); return new Map<string, Item[]>();
}); });
vi.spyOn(insuranceController, "populateParentAttachmentsMap").mockImplementation(mockPopulateParentAttachmentsMap); vi.spyOn(insuranceController, "populateParentAttachmentsMap").mockImplementation(
mockPopulateParentAttachmentsMap,
);
// Execute the method. // Execute the method.
const result = insuranceController.findItemsToDelete(insured); const result = insuranceController.findItemsToDelete(insured);
@ -491,12 +520,12 @@ describe("InsuranceController", () =>
// Add all items to the toDelete set. Not realistic, but it's fine for this test. // Add all items to the toDelete set. Not realistic, but it's fine for this test.
const mockProcessRegularItems = vi.fn((insured, toDelete) => const mockProcessRegularItems = vi.fn((insured, toDelete) =>
{ {
insured.items.forEach(item => toDelete.add(item._id)); insured.items.forEach((item) => toDelete.add(item._id));
}); });
vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems); vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems);
const mockProcessAttachments = vi.fn((parentAttachmentsMap, itemsMap, traderId, toDelete) => const mockProcessAttachments = vi.fn((parentAttachmentsMap, itemsMap, traderId, toDelete) =>
{ {
insured.items.forEach(item => toDelete.add(item._id)); insured.items.forEach((item) => toDelete.add(item._id));
}); });
vi.spyOn(insuranceController, "processAttachments").mockImplementation(mockProcessAttachments); vi.spyOn(insuranceController, "processAttachments").mockImplementation(mockProcessAttachments);
@ -511,7 +540,7 @@ describe("InsuranceController", () =>
// Verify that the result is correct. // Verify that the result is correct.
expect(result.size).toBe(numberOfItems); expect(result.size).toBe(numberOfItems);
expect(result).toEqual(new Set(insured.items.map(item => item._id))); expect(result).toEqual(new Set(insured.items.map((item) => item._id)));
}); });
it("should return an empty set if no items are to be deleted", () => it("should return an empty set if no items are to be deleted", () =>
@ -523,8 +552,12 @@ describe("InsuranceController", () =>
const mockPopulateParentAttachmentsMap = vi.spyOn(insuranceController, "populateParentAttachmentsMap"); const mockPopulateParentAttachmentsMap = vi.spyOn(insuranceController, "populateParentAttachmentsMap");
// Don't add any items to the toDelete set. // Don't add any items to the toDelete set.
const mockProcessRegularItems = vi.spyOn(insuranceController, "processRegularItems").mockImplementation(vi.fn()); const mockProcessRegularItems = vi.spyOn(insuranceController, "processRegularItems").mockImplementation(
const mockProcessAttachments = vi.spyOn(insuranceController, "processAttachments").mockImplementation(vi.fn()); vi.fn(),
);
const mockProcessAttachments = vi.spyOn(insuranceController, "processAttachments").mockImplementation(
vi.fn(),
);
// Execute the method. // Execute the method.
const result = insuranceController.findItemsToDelete(insured); const result = insuranceController.findItemsToDelete(insured);
@ -551,12 +584,12 @@ describe("InsuranceController", () =>
// Add all items to the toDelete set. Not realistic, but it's fine for this test. // Add all items to the toDelete set. Not realistic, but it's fine for this test.
const mockProcessRegularItems = vi.fn((insured, toDelete) => const mockProcessRegularItems = vi.fn((insured, toDelete) =>
{ {
insured.items.forEach(item => toDelete.add(item._id)); insured.items.forEach((item) => toDelete.add(item._id));
}); });
vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems); vi.spyOn(insuranceController, "processRegularItems").mockImplementation(mockProcessRegularItems);
const mockProcessAttachments = vi.fn((parentAttachmentsMap, itemsMap, traderId, toDelete) => const mockProcessAttachments = vi.fn((parentAttachmentsMap, itemsMap, traderId, toDelete) =>
{ {
insured.items.forEach(item => toDelete.add(item._id)); insured.items.forEach((item) => toDelete.add(item._id));
}); });
vi.spyOn(insuranceController, "processAttachments").mockImplementation(mockProcessAttachments); vi.spyOn(insuranceController, "processAttachments").mockImplementation(mockProcessAttachments);
@ -595,12 +628,12 @@ describe("InsuranceController", () =>
"da8cde1b3024c336f6e06152", "da8cde1b3024c336f6e06152",
"bc041c0011d76f714b898400", "bc041c0011d76f714b898400",
"9f8d7880a6e0a47a211ec5d3", "9f8d7880a6e0a47a211ec5d3",
"db2ef9442178910eba985b51" "db2ef9442178910eba985b51",
]; ];
validAttachmentTemplates.forEach(value => validAttachmentTemplates.forEach((value) =>
{ {
// Verify that each template is present in the array of attachments. // Verify that each template is present in the array of attachments.
expect(gun.some(item => item._id === value)).toBe(true); expect(gun.some((item) => item._id === value)).toBe(true);
}); });
}); });
@ -625,11 +658,11 @@ describe("InsuranceController", () =>
"1e0b177df108c0c117028812", "1e0b177df108c0c117028812",
"c9278dd8251e99578bf7a274", "c9278dd8251e99578bf7a274",
"402b4086535a50ef7d9cef88", "402b4086535a50ef7d9cef88",
"566335b3df586f34b47f5e35" "566335b3df586f34b47f5e35",
]; ];
invalidAttachmentTemplates.forEach(value => invalidAttachmentTemplates.forEach((value) =>
{ {
expect(gun.every(item => item._id !== value)).toBe(true); expect(gun.every((item) => item._id !== value)).toBe(true);
}); });
}); });
@ -655,12 +688,12 @@ describe("InsuranceController", () =>
"dc565f750342cb2d19eeda06", "dc565f750342cb2d19eeda06",
"e9ff62601669d9e2ea9c2fbb", "e9ff62601669d9e2ea9c2fbb",
"ac134d7cf6c9d8e25edd0015", "ac134d7cf6c9d8e25edd0015",
"22274b895ecc80d51c3cba1c" "22274b895ecc80d51c3cba1c",
]; ];
validAttachmentTemplates.forEach(value => validAttachmentTemplates.forEach((value) =>
{ {
// Verify that each template is present in the array of attachments. // Verify that each template is present in the array of attachments.
expect(gun.some(item => item._id === value)).toBe(true); expect(gun.some((item) => item._id === value)).toBe(true);
}); });
}); });
@ -678,7 +711,7 @@ describe("InsuranceController", () =>
expect(result.size).toBe(6); // There are 6 base-level items in this insurance package. expect(result.size).toBe(6); // There are 6 base-level items in this insurance package.
const gun = result.get("351180f3248d45c71cb2ebdc"); const gun = result.get("351180f3248d45c71cb2ebdc");
expect(insured.items.find(item => item._id === "351180f3248d45c71cb2ebdc").slotId).toBe("main"); expect(insured.items.find((item) => item._id === "351180f3248d45c71cb2ebdc").slotId).toBe("main");
expect(gun.length).toBe(14); // This AS VAL has 14 valid attachments. expect(gun.length).toBe(14); // This AS VAL has 14 valid attachments.
}); });
@ -727,7 +760,10 @@ describe("InsuranceController", () =>
// Mock helper methods. // Mock helper methods.
const mockIsAttachmentAttached = vi.spyOn(insuranceController.itemHelper, "isAttachmentAttached"); const mockIsAttachmentAttached = vi.spyOn(insuranceController.itemHelper, "isAttachmentAttached");
const mockFindAndReturnChildrenAsItems = vi.spyOn(insuranceController.itemHelper, "findAndReturnChildrenAsItems"); const mockFindAndReturnChildrenAsItems = vi.spyOn(
insuranceController.itemHelper,
"findAndReturnChildrenAsItems",
);
// Mock rollForDelete to return true for all items. Not realistic, but it's fine for this test. // Mock rollForDelete to return true for all items. Not realistic, but it's fine for this test.
const mockRollForDelete = vi.spyOn(insuranceController, "rollForDelete").mockReturnValue(true); const mockRollForDelete = vi.spyOn(insuranceController, "rollForDelete").mockReturnValue(true);
@ -741,7 +777,7 @@ describe("InsuranceController", () =>
expect(mockRollForDelete).toHaveBeenCalledTimes(numberOfItems); expect(mockRollForDelete).toHaveBeenCalledTimes(numberOfItems);
// Verify that all items were added to the toDelete set. // Verify that all items were added to the toDelete set.
expect(toDelete).toEqual(new Set(insured.items.map(item => item._id))); expect(toDelete).toEqual(new Set(insured.items.map((item) => item._id)));
}); });
it("should not roll attached attachments", () => it("should not roll attached attachments", () =>
@ -783,7 +819,7 @@ describe("InsuranceController", () =>
insuranceController.processRegularItems(insured, toDelete); insuranceController.processRegularItems(insured, toDelete);
// Verify that all items were added to the toDelete set. // Verify that all items were added to the toDelete set.
expect(toDelete).toEqual(new Set(insured.items.map(item => item._id))); expect(toDelete).toEqual(new Set(insured.items.map((item) => item._id)));
}); });
}); });
@ -827,7 +863,9 @@ describe("InsuranceController", () =>
const parentItem = itemsMap.get(parentId); const parentItem = itemsMap.get(parentId);
if (parentItem) if (parentItem)
{ {
const expectedMessage = `Processing attachments for parent item: ${itemHelper.getItemName(parentItem._tpl)}`; const expectedMessage = `Processing attachments for parent item: ${
itemHelper.getItemName(parentItem._tpl)
}`;
expect(mockLoggerDebug).toHaveBeenCalledWith(expectedMessage); expect(mockLoggerDebug).toHaveBeenCalledWith(expectedMessage);
} }
} }
@ -911,14 +949,16 @@ describe("InsuranceController", () =>
const attachments = parentToAttachmentMap.values().next().value; const attachments = parentToAttachmentMap.values().next().value;
// Set the maxPrice of the first two attachments to null. // Set the maxPrice of the first two attachments to null.
vi.spyOn(insuranceController.itemHelper, "getItemMaxPrice").mockReturnValueOnce(null).mockReturnValueOnce(null); vi.spyOn(insuranceController.itemHelper, "getItemMaxPrice").mockReturnValueOnce(null).mockReturnValueOnce(
null,
);
// Execute the method. // Execute the method.
const sortedAttachments = insuranceController.sortAttachmentsByPrice(attachments); const sortedAttachments = insuranceController.sortAttachmentsByPrice(attachments);
// Verify that the attachments with null maxPrice are at the bottom of the list // Verify that the attachments with null maxPrice are at the bottom of the list
const nullPriceAttachments = sortedAttachments.slice(-2); const nullPriceAttachments = sortedAttachments.slice(-2);
nullPriceAttachments.forEach(attachment => nullPriceAttachments.forEach((attachment) =>
{ {
expect(attachment.maxPrice).toBeNull(); expect(attachment.maxPrice).toBeNull();
}); });
@ -936,8 +976,8 @@ describe("InsuranceController", () =>
it("should log details for each attachment", () => it("should log details for each attachment", () =>
{ {
const attachments = [ const attachments = [
{ _id: "item1", name: "Item 1", maxPrice: 100 }, {_id: "item1", name: "Item 1", maxPrice: 100},
{ _id: "item2", name: "Item 2", maxPrice: 200 } {_id: "item2", name: "Item 2", maxPrice: 200},
]; ];
// Mock the logger.debug function. // Mock the logger.debug function.
@ -1096,9 +1136,9 @@ describe("InsuranceController", () =>
insuranceController.removeItemsFromInsurance(insured, toDelete); insuranceController.removeItemsFromInsurance(insured, toDelete);
// Ensure that the items in the toDelete set are not present in the insured items array. // Ensure that the items in the toDelete set are not present in the insured items array.
toDelete.forEach(toDeleteId => toDelete.forEach((toDeleteId) =>
{ {
expect(insured.items.some(item => item._id === toDeleteId)).toBe(false); expect(insured.items.some((item) => item._id === toDeleteId)).toBe(false);
}); });
}); });
@ -1120,7 +1160,7 @@ describe("InsuranceController", () =>
const insured = insuranceFixture[0]; const insured = insuranceFixture[0];
const originalCount = insured.items.length; const originalCount = insured.items.length;
const toDelete = new Set<string>(); const toDelete = new Set<string>();
insured.items.forEach(item => toDelete.add(item._id)); insured.items.forEach((item) => toDelete.add(item._id));
// All of the items should be added to the toDelete set. // All of the items should be added to the toDelete set.
expect(originalCount).toBe(toDelete.size); expect(originalCount).toBe(toDelete.size);
@ -1146,7 +1186,9 @@ describe("InsuranceController", () =>
insured.items[0].slotId = "main"; // Should not be "hideout". insured.items[0].slotId = "main"; // Should not be "hideout".
// Iterate over the items and find an individual orphaned item. // Iterate over the items and find an individual orphaned item.
const orphanedItem = insured.items.find(item => !insured.items.some(parent => parent._id === item.parentId)); const orphanedItem = insured.items.find((item) =>
!insured.items.some((parent) => parent._id === item.parentId)
);
// Setup tests to verify that the orphaned item we added is in fact orphaned. // Setup tests to verify that the orphaned item we added is in fact orphaned.
expect(orphanedItem.parentId).toBe(insured.items[0].parentId); expect(orphanedItem.parentId).toBe(insured.items[0].parentId);
@ -1184,7 +1226,9 @@ describe("InsuranceController", () =>
insured.items[0].location = {x: 1, y: 2, r: 3, isSearched: true}; // Should be removed. insured.items[0].location = {x: 1, y: 2, r: 3, isSearched: true}; // Should be removed.
// Iterate over the items and find an individual orphaned item. // Iterate over the items and find an individual orphaned item.
const orphanedItem = insured.items.find(item => !insured.items.some(parent => parent._id === item.parentId)); const orphanedItem = insured.items.find((item) =>
!insured.items.some((parent) => parent._id === item.parentId)
);
// Setup tests to verify that the orphaned item we added is in fact orphaned. // Setup tests to verify that the orphaned item we added is in fact orphaned.
expect(orphanedItem.parentId).toBe(insured.items[0].parentId); expect(orphanedItem.parentId).toBe(insured.items[0].parentId);
@ -1275,7 +1319,7 @@ describe("InsuranceController", () =>
insuranceFailedTpl, insuranceFailedTpl,
insurance.items, insurance.items,
insurance.messageContent.maxStorageTime, insurance.messageContent.maxStorageTime,
insurance.messageContent.systemData insurance.messageContent.systemData,
); );
}); });
@ -1309,7 +1353,7 @@ describe("InsuranceController", () =>
insurance.messageContent.templateId, insurance.messageContent.templateId,
insurance.items, insurance.items,
insurance.messageContent.maxStorageTime, insurance.messageContent.maxStorageTime,
insurance.messageContent.systemData insurance.messageContent.systemData,
); );
}); });
}); });
@ -1322,8 +1366,8 @@ describe("InsuranceController", () =>
const traderId = "54cb57776803fa99248b456e"; // Therapist (85% return chance) const traderId = "54cb57776803fa99248b456e"; // Therapist (85% return chance)
insuranceController.insuranceConfig = { insuranceController.insuranceConfig = {
returnChancePercent: { returnChancePercent: {
[traderId]: 85 // Force 85% return chance [traderId]: 85, // Force 85% return chance
} },
}; };
// Execute the method. // Execute the method.
@ -1339,8 +1383,8 @@ describe("InsuranceController", () =>
const traderId = "54cb57776803fa99248b456e"; // Therapist (85% return chance) const traderId = "54cb57776803fa99248b456e"; // Therapist (85% return chance)
insuranceController.insuranceConfig = { insuranceController.insuranceConfig = {
returnChancePercent: { returnChancePercent: {
[traderId]: 85 // Force 85% return chance [traderId]: 85, // Force 85% return chance
} },
}; };
// Execute the method. // Execute the method.
@ -1356,8 +1400,8 @@ describe("InsuranceController", () =>
const traderId = "54cb57776803fa99248b456e"; // Therapist (85% return chance) const traderId = "54cb57776803fa99248b456e"; // Therapist (85% return chance)
insuranceController.insuranceConfig = { insuranceController.insuranceConfig = {
returnChancePercent: { returnChancePercent: {
[traderId]: 85 // Force 85% return chance [traderId]: 85, // Force 85% return chance
} },
}; };
// Execute the method. // Execute the method.
@ -1394,7 +1438,13 @@ describe("InsuranceController", () =>
describe("insure", () => describe("insure", () =>
{ {
let pmcData: any, body: any, sessionId: string, insuranceController: any, mockGetPremium: any, mockPayMoney: any, mockGetOutput: any; let pmcData: any,
body: any,
sessionId: string,
insuranceController: any,
mockGetPremium: any,
mockPayMoney: any,
mockGetOutput: any;
beforeEach(() => beforeEach(() =>
{ {
@ -1404,15 +1454,15 @@ describe("InsuranceController", () =>
pmcData = { pmcData = {
Inventory: { Inventory: {
items: [ items: [
{ _id: "item1", otherProps: "value1" }, {_id: "item1", otherProps: "value1"},
{ _id: "item2", otherProps: "value2" } {_id: "item2", otherProps: "value2"},
] ],
}, },
InsuredItems: [] InsuredItems: [],
}; };
body = { body = {
items: ["item1", "item2"], items: ["item1", "item2"],
tid: "someTraderId" tid: "someTraderId",
}; };
sessionId = "session-id"; sessionId = "session-id";
@ -1420,11 +1470,11 @@ describe("InsuranceController", () =>
mockGetPremium = vi.spyOn(insuranceController.insuranceService, "getPremium").mockReturnValue(100); mockGetPremium = vi.spyOn(insuranceController.insuranceService, "getPremium").mockReturnValue(100);
mockPayMoney = vi.spyOn(insuranceController.paymentService, "payMoney").mockReturnValue({ mockPayMoney = vi.spyOn(insuranceController.paymentService, "payMoney").mockReturnValue({
warnings: [], warnings: [],
otherProperty: "property-value" otherProperty: "property-value",
}); });
mockGetOutput = vi.spyOn(insuranceController.eventOutputHolder, "getOutput").mockReturnValue({ mockGetOutput = vi.spyOn(insuranceController.eventOutputHolder, "getOutput").mockReturnValue({
warnings: [], warnings: [],
otherProperty: "property-value" otherProperty: "property-value",
}); });
}); });
@ -1439,20 +1489,21 @@ describe("InsuranceController", () =>
pmcData, pmcData,
{ {
scheme_items: [ scheme_items: [
{ id: "item1", count: 100 }, {id: "item1", count: 100},
{ id: "item2", count: 100 } {id: "item2", count: 100},
], ],
tid: "someTraderId", tid: "someTraderId",
Action: "", Action: "",
type: "", type: "",
item_id: "", item_id: "",
count: 0, count: 0,
scheme_id: 0 scheme_id: 0,
}, },
sessionId, { sessionId,
{
warnings: [], warnings: [],
otherProperty: "property-value" otherProperty: "property-value",
} },
); );
}); });
@ -1479,15 +1530,15 @@ describe("InsuranceController", () =>
// Define the expected payment options structure based on the setup data. // Define the expected payment options structure based on the setup data.
const expectedPaymentOptions = { const expectedPaymentOptions = {
scheme_items: [ scheme_items: [
{ id: "item1", count: 100 }, {id: "item1", count: 100},
{ id: "item2", count: 100 } {id: "item2", count: 100},
], ],
tid: body.tid, tid: body.tid,
Action: "", Action: "",
type: "", type: "",
item_id: "", item_id: "",
count: 0, count: 0,
scheme_id: 0 scheme_id: 0,
}; };
// Verify that the paymentService's payMoney method was called once with the expected parameters. // Verify that the paymentService's payMoney method was called once with the expected parameters.
@ -1498,7 +1549,7 @@ describe("InsuranceController", () =>
pmcData, pmcData,
expectedPaymentOptions, expectedPaymentOptions,
sessionId, sessionId,
mockGetOutput.mock.results[0].value mockGetOutput.mock.results[0].value,
); );
}); });
@ -1508,7 +1559,7 @@ describe("InsuranceController", () =>
insuranceController.insure(pmcData, body, sessionId); insuranceController.insure(pmcData, body, sessionId);
// Verify that the InsuredItems array has been populated with the correct items. // Verify that the InsuredItems array has been populated with the correct items.
const insuredItemIds = pmcData.InsuredItems.map(insuredItem => insuredItem.itemId); const insuredItemIds = pmcData.InsuredItems.map((insuredItem) => insuredItem.itemId);
expect(insuredItemIds).toContain("item1"); expect(insuredItemIds).toContain("item1");
expect(insuredItemIds).toContain("item2"); expect(insuredItemIds).toContain("item2");
@ -1523,9 +1574,9 @@ describe("InsuranceController", () =>
warnings: [{ warnings: [{
index: 0, index: 0,
errmsg: "Not enough money to complete transaction", errmsg: "Not enough money to complete transaction",
code: 500 code: 500,
}], }],
otherProperty: "property-value" otherProperty: "property-value",
}; };
mockPayMoney.mockReturnValue(expectedPayMoneyReturn); mockPayMoney.mockReturnValue(expectedPayMoneyReturn);
@ -1546,9 +1597,9 @@ describe("InsuranceController", () =>
warnings: [{ warnings: [{
index: 0, index: 0,
errmsg: "Not enough money to complete transaction", errmsg: "Not enough money to complete transaction",
code: 500 code: 500,
}], }],
otherProperty: "property-value" otherProperty: "property-value",
}; };
mockPayMoney.mockReturnValue(expectedPayMoneyReturn); mockPayMoney.mockReturnValue(expectedPayMoneyReturn);
@ -1573,17 +1624,17 @@ describe("InsuranceController", () =>
vi.spyOn(insuranceController.profileHelper, "getPmcProfile").mockReturnValue({ vi.spyOn(insuranceController.profileHelper, "getPmcProfile").mockReturnValue({
Inventory: { Inventory: {
items: [ items: [
{ _id: "itemId1", _tpl: "itemTpl1", otherProperty: "property-value1" }, {_id: "itemId1", _tpl: "itemTpl1", otherProperty: "property-value1"},
{ _id: "itemId2", _tpl: "itemTpl2", otherProperty: "property-value2" }, {_id: "itemId2", _tpl: "itemTpl2", otherProperty: "property-value2"},
{ _id: "itemId3", _tpl: "itemTpl3", otherProperty: "property-value3" } {_id: "itemId3", _tpl: "itemTpl3", otherProperty: "property-value3"},
] ],
} },
}); });
}); });
it("should return an empty object if no traders and items are specified", () => it("should return an empty object if no traders and items are specified", () =>
{ {
const request = { traders: [], items: [] }; const request = {traders: [], items: []};
const expected = {}; const expected = {};
const result = insuranceController.cost(request, sessionId); const result = insuranceController.cost(request, sessionId);
@ -1593,8 +1644,8 @@ describe("InsuranceController", () =>
it("should return an empty object if no items are specified", () => it("should return an empty object if no items are specified", () =>
{ {
const request = { traders: ["prapor"], items: [] }; const request = {traders: ["prapor"], items: []};
const expected = { prapor: {} }; const expected = {prapor: {}};
const result = insuranceController.cost(request, sessionId); const result = insuranceController.cost(request, sessionId);
@ -1603,7 +1654,7 @@ describe("InsuranceController", () =>
it("should return an empty object if no trader is specified but items are", () => it("should return an empty object if no trader is specified but items are", () =>
{ {
const request = { traders: [], items: ["itemId1", "itemId2"] }; const request = {traders: [], items: ["itemId1", "itemId2"]};
const expected = {}; const expected = {};
const result = insuranceController.cost(request, sessionId); const result = insuranceController.cost(request, sessionId);
@ -1615,11 +1666,11 @@ describe("InsuranceController", () =>
{ {
const request = { const request = {
traders: ["prapor", "therapist"], traders: ["prapor", "therapist"],
items: ["itemId1", "itemId2", "itemId3"] items: ["itemId1", "itemId2", "itemId3"],
}; };
const expected = { const expected = {
prapor: { itemTpl1: 100, itemTpl2: 200, itemTpl3: 300 }, prapor: {itemTpl1: 100, itemTpl2: 200, itemTpl3: 300},
therapist: { itemTpl1: 150, itemTpl2: 250, itemTpl3: 350 } therapist: {itemTpl1: 150, itemTpl2: 250, itemTpl3: 350},
}; };
// Mock the InsuranceService.getPremium method to return the expected values. // Mock the InsuranceService.getPremium method to return the expected values.
@ -1643,11 +1694,11 @@ describe("InsuranceController", () =>
items: [ items: [
"itemId1", "itemId1",
"itemId2", "itemId2",
"itemId4" // Doesn't exist in the player's inventory. "itemId4", // Doesn't exist in the player's inventory.
] ],
}; };
const expected = { const expected = {
prapor: { itemTpl1: 100, itemTpl2: 200 } prapor: {itemTpl1: 100, itemTpl2: 200},
}; };
// Mock the InsuranceService.getPremium method to return the expected values. // Mock the InsuranceService.getPremium method to return the expected values.

View File

@ -1,9 +1,9 @@
/* eslint-disable @typescript-eslint/naming-convention */ /* eslint-disable @typescript-eslint/naming-convention */
import "reflect-metadata"; import "reflect-metadata";
import { container } from "tsyringe";
import { vi, beforeEach, afterEach, describe, expect, it } from "vitest";
import { BotGenerator } from "@spt-aki/generators/BotGenerator"; import { BotGenerator } from "@spt-aki/generators/BotGenerator";
import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { IPmcData } from "@spt-aki/models/eft/common/IPmcData";
import { container } from "tsyringe";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
describe("BotGenerator", () => describe("BotGenerator", () =>
{ {
@ -62,15 +62,15 @@ describe("BotGenerator", () =>
const mockPlayerProfile = { const mockPlayerProfile = {
Info: { Info: {
Nickname: "Player Nickname", Nickname: "Player Nickname",
Level: 1 Level: 1,
} },
}; };
vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(<IPmcData>mockPlayerProfile); vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(<IPmcData>mockPlayerProfile);
const botJsonTemplate = { const botJsonTemplate = {
firstName: ["test"], firstName: ["test"],
lastName: [] lastName: [],
}; };
const sessionId = "sessionId"; const sessionId = "sessionId";
@ -88,14 +88,14 @@ describe("BotGenerator", () =>
const mockPlayerProfile = { const mockPlayerProfile = {
Info: { Info: {
Nickname: "Player Nickname", Nickname: "Player Nickname",
Level: 1 Level: 1,
} },
}; };
vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(<IPmcData>mockPlayerProfile); vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(<IPmcData>mockPlayerProfile);
const botJsonTemplate = { const botJsonTemplate = {
firstName: ["test"], firstName: ["test"],
lastName: [] lastName: [],
}; };
const sessionId = "sessionId"; const sessionId = "sessionId";
@ -114,15 +114,15 @@ describe("BotGenerator", () =>
const mockPlayerProfile = { const mockPlayerProfile = {
Info: { Info: {
Nickname: "Player", Nickname: "Player",
Level: 1 Level: 1,
} },
}; };
vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(<IPmcData>mockPlayerProfile); vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(<IPmcData>mockPlayerProfile);
vi.spyOn(botGenerator.localisationService, "getRandomTextThatMatchesPartialKey").mockReturnValue("test"); vi.spyOn(botGenerator.localisationService, "getRandomTextThatMatchesPartialKey").mockReturnValue("test");
const botJsonTemplate = { const botJsonTemplate = {
firstName: ["Player"], firstName: ["Player"],
lastName: [] lastName: [],
}; };
const sessionId = "sessionId"; const sessionId = "sessionId";
@ -140,14 +140,14 @@ describe("BotGenerator", () =>
const mockPlayerProfile = { const mockPlayerProfile = {
Info: { Info: {
Nickname: "Player", Nickname: "Player",
Level: 1 Level: 1,
} },
}; };
vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(<IPmcData>mockPlayerProfile); vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(<IPmcData>mockPlayerProfile);
const botJsonTemplate = { const botJsonTemplate = {
firstName: ["test"], firstName: ["test"],
lastName: [] lastName: [],
}; };
const sessionId = "sessionId"; const sessionId = "sessionId";
@ -167,14 +167,14 @@ describe("BotGenerator", () =>
const mockPlayerProfile = { const mockPlayerProfile = {
Info: { Info: {
Nickname: "Player", Nickname: "Player",
Level: 1 Level: 1,
} },
}; };
vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(<IPmcData>mockPlayerProfile); vi.spyOn(botGenerator.profileHelper, "getPmcProfile").mockReturnValue(<IPmcData>mockPlayerProfile);
const botJsonTemplate = { const botJsonTemplate = {
firstName: ["test"], firstName: ["test"],
lastName: [] lastName: [],
}; };
const sessionId = "sessionId"; const sessionId = "sessionId";

View File

@ -1,6 +1,6 @@
import "reflect-metadata"; import "reflect-metadata";
import { container } from "tsyringe"; import { container } from "tsyringe";
import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { BotLevelGenerator } from "@spt-aki/generators/BotLevelGenerator"; import { BotLevelGenerator } from "@spt-aki/generators/BotLevelGenerator";
import { MinMax } from "@spt-aki/models/common/MinMax"; import { MinMax } from "@spt-aki/models/common/MinMax";
@ -29,7 +29,7 @@ describe("BotLevelGenerator", () =>
{ {
const levelDetails: MinMax = { const levelDetails: MinMax = {
min: 5, min: 5,
max: 10 max: 10,
}; };
const botGenerationDetails: BotGenerationDetails = { const botGenerationDetails: BotGenerationDetails = {
@ -40,7 +40,7 @@ describe("BotLevelGenerator", () =>
botRelativeLevelDeltaMax: 0, botRelativeLevelDeltaMax: 0,
botCountToGenerate: 0, botCountToGenerate: 0,
botDifficulty: "", botDifficulty: "",
isPlayerScav: false isPlayerScav: false,
}; };
const result = botLevelGenerator.generateBotLevel(levelDetails, botGenerationDetails, null); const result = botLevelGenerator.generateBotLevel(levelDetails, botGenerationDetails, null);
@ -55,7 +55,7 @@ describe("BotLevelGenerator", () =>
{ {
const levelDetails: MinMax = { const levelDetails: MinMax = {
min: 5, min: 5,
max: 10 max: 10,
}; };
const expTable = databaseServer.getTables().globals.config.exp.level.exp_table; const expTable = databaseServer.getTables().globals.config.exp.level.exp_table;
@ -69,14 +69,19 @@ describe("BotLevelGenerator", () =>
{ {
const levelDetails: MinMax = { const levelDetails: MinMax = {
min: 100, min: 100,
max: 100 max: 100,
}; };
const expTable = databaseServer.getTables().globals.config.exp.level.exp_table; const expTable = databaseServer.getTables().globals.config.exp.level.exp_table;
const playerLevel = 100; const playerLevel = 100;
const relativeDeltaMax = 5; const relativeDeltaMax = 5;
const result = botLevelGenerator.getHighestRelativeBotLevel(playerLevel, relativeDeltaMax, levelDetails, expTable); const result = botLevelGenerator.getHighestRelativeBotLevel(
playerLevel,
relativeDeltaMax,
levelDetails,
expTable,
);
expect(result).toBe(79); expect(result).toBe(79);
}); });

View File

@ -1,6 +1,6 @@
import "reflect-metadata"; import "reflect-metadata";
import { container } from "tsyringe"; import { container } from "tsyringe";
import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { BotHelper } from "@spt-aki/helpers/BotHelper"; import { BotHelper } from "@spt-aki/helpers/BotHelper";

View File

@ -1,6 +1,6 @@
import "reflect-metadata"; import "reflect-metadata";
import { container } from "tsyringe"; import { container } from "tsyringe";
import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { HandbookHelper } from "@spt-aki/helpers/HandbookHelper"; import { HandbookHelper } from "@spt-aki/helpers/HandbookHelper";
import { Money } from "@spt-aki/models/enums/Money"; import { Money } from "@spt-aki/models/enums/Money";

View File

@ -1,6 +1,6 @@
import "reflect-metadata"; import "reflect-metadata";
import { container } from "tsyringe"; import { container } from "tsyringe";
import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { InRaidHelper } from "@spt-aki/helpers/InRaidHelper"; import { InRaidHelper } from "@spt-aki/helpers/InRaidHelper";
import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer";
@ -27,12 +27,12 @@ describe("InRaidHelper", () =>
const postRaidPlayerVictims = [ const postRaidPlayerVictims = [
{ {
Side: "Savage", Side: "Savage",
Role: "assault" Role: "assault",
}, },
{ {
Side: "Savage", Side: "Savage",
Role: "assault" Role: "assault",
} },
]; // Kills ]; // Kills
const databaseServer = container.resolve<DatabaseServer>("DatabaseServer"); const databaseServer = container.resolve<DatabaseServer>("DatabaseServer");
@ -49,12 +49,12 @@ describe("InRaidHelper", () =>
const postRaidPlayerVictims = [ const postRaidPlayerVictims = [
{ {
Side: "Usec", Side: "Usec",
Role: "sptUsec" Role: "sptUsec",
}, },
{ {
Side: "Bear", Side: "Bear",
Role: "sptBear" Role: "sptBear",
} },
]; // Kills ]; // Kills
const databaseServer = container.resolve<DatabaseServer>("DatabaseServer"); const databaseServer = container.resolve<DatabaseServer>("DatabaseServer");
@ -72,29 +72,32 @@ describe("InRaidHelper", () =>
const postRaidPlayerVictims = [ const postRaidPlayerVictims = [
{ {
Side: "Usec", Side: "Usec",
Role: "sptUsec" Role: "sptUsec",
}, },
{ {
Side: "savage", Side: "savage",
Role: "assault" Role: "assault",
}, },
{ {
Side: "savage", Side: "savage",
Role: "bossBoar" Role: "bossBoar",
}, },
{ {
Side: "savage", Side: "savage",
Role: "assault" Role: "assault",
} },
]; // Kills ]; // Kills
const databaseServer = container.resolve<DatabaseServer>("DatabaseServer"); const databaseServer = container.resolve<DatabaseServer>("DatabaseServer");
const usecStandingChangeOnKill = databaseServer.getTables().bots.types.bear.experience.standingForKill; const usecStandingChangeOnKill = databaseServer.getTables().bots.types.bear.experience.standingForKill;
const scavStandingChangeOnKill = databaseServer.getTables().bots.types.assault.experience.standingForKill; const scavStandingChangeOnKill = databaseServer.getTables().bots.types.assault.experience.standingForKill;
const bossBoarStandingChangeOnKill = databaseServer.getTables().bots.types.bossboar.experience.standingForKill; const bossBoarStandingChangeOnKill =
databaseServer.getTables().bots.types.bossboar.experience.standingForKill;
const result = inraidHelper.calculateFenceStandingChangeFromKills(fenceStanding, postRaidPlayerVictims); const result = inraidHelper.calculateFenceStandingChangeFromKills(fenceStanding, postRaidPlayerVictims);
expect(result).toBe(usecStandingChangeOnKill + (scavStandingChangeOnKill * 2) + bossBoarStandingChangeOnKill); expect(result).toBe(
usecStandingChangeOnKill + (scavStandingChangeOnKill * 2) + bossBoarStandingChangeOnKill,
);
expect(result).lessThan(0); expect(result).lessThan(0);
}); });
@ -104,12 +107,14 @@ describe("InRaidHelper", () =>
const postRaidPlayerVictims = [ const postRaidPlayerVictims = [
{ {
Side: "savage", Side: "savage",
Role: "testRole" Role: "testRole",
} },
]; // Kills ]; // Kills
// Fake getFenceStandingChangeForKillAsScav() returning null // Fake getFenceStandingChangeForKillAsScav() returning null
vi.spyOn(inraidHelper, "getFenceStandingChangeForKillAsScav").mockReturnValueOnce(null).mockReturnValueOnce(null); vi.spyOn(inraidHelper, "getFenceStandingChangeForKillAsScav").mockReturnValueOnce(null).mockReturnValueOnce(
null,
);
const result = inraidHelper.calculateFenceStandingChangeFromKills(fenceStanding, postRaidPlayerVictims); const result = inraidHelper.calculateFenceStandingChangeFromKills(fenceStanding, postRaidPlayerVictims);
expect(result).toBe(0); expect(result).toBe(0);
}); });

View File

@ -1,12 +1,12 @@
import "reflect-metadata"; import "reflect-metadata";
import { container } from "tsyringe"; import { container } from "tsyringe";
import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ItemHelper } from "@spt-aki/helpers/ItemHelper"; import { ItemHelper } from "@spt-aki/helpers/ItemHelper";
import { Item, Repairable } from "@spt-aki/models/eft/common/tables/IItem"; import { Item, Repairable } from "@spt-aki/models/eft/common/tables/IItem";
import { ITemplateItem } from "@spt-aki/models/eft/common/tables/ITemplateItem";
import { DatabaseServer } from "@spt-aki/servers/DatabaseServer"; import { DatabaseServer } from "@spt-aki/servers/DatabaseServer";
import { HashUtil } from "@spt-aki/utils/HashUtil"; import { HashUtil } from "@spt-aki/utils/HashUtil";
import { ITemplateItem } from "@spt-aki/models/eft/common/tables/ITemplateItem";
describe("ItemHelper", () => describe("ItemHelper", () =>
{ {
@ -251,7 +251,7 @@ describe("ItemHelper", () =>
{ {
const initialItem: Item = { const initialItem: Item = {
_id: "", _id: "",
_tpl: "" _tpl: "",
}; };
const fixedItem = itemHelper.fixItemStackCount(initialItem); const fixedItem = itemHelper.fixItemStackCount(initialItem);
@ -264,7 +264,7 @@ describe("ItemHelper", () =>
const initialItem: Item = { const initialItem: Item = {
_id: "", _id: "",
_tpl: "", _tpl: "",
upd: {} upd: {},
}; };
const fixedItem = itemHelper.fixItemStackCount(initialItem); const fixedItem = itemHelper.fixItemStackCount(initialItem);
@ -278,8 +278,8 @@ describe("ItemHelper", () =>
_id: "", _id: "",
_tpl: "", _tpl: "",
upd: { upd: {
StackObjectsCount: 5 StackObjectsCount: 5,
} },
}; };
const fixedItem = itemHelper.fixItemStackCount(initialItem); const fixedItem = itemHelper.fixItemStackCount(initialItem);
@ -324,7 +324,6 @@ describe("ItemHelper", () =>
// Restore the original behavior // Restore the original behavior
loggerWarningSpy.mockRestore(); loggerWarningSpy.mockRestore();
}); });
}); });
describe("getItems", () => describe("getItems", () =>
@ -420,7 +419,7 @@ describe("ItemHelper", () =>
const itemId = container.resolve<HashUtil>("HashUtil").generate(); const itemId = container.resolve<HashUtil>("HashUtil").generate();
const item: Item = { const item: Item = {
_id: itemId, _id: itemId,
_tpl: "590c657e86f77412b013051d" // "Grizzly medical kit" _tpl: "590c657e86f77412b013051d", // "Grizzly medical kit"
}; };
const result = itemHelper.getItemQualityModifier(item); const result = itemHelper.getItemQualityModifier(item);
@ -433,8 +432,8 @@ describe("ItemHelper", () =>
const itemId = container.resolve<HashUtil>("HashUtil").generate(); const itemId = container.resolve<HashUtil>("HashUtil").generate();
const item: Item = { const item: Item = {
_id: itemId, _id: itemId,
_tpl: "590c657e86f77412b013051d", // "Grizzly medical kit" _tpl: "590c657e86f77412b013051d", // "Grizzly medical kit"
upd: {} upd: {},
}; };
const result = itemHelper.getItemQualityModifier(item); const result = itemHelper.getItemQualityModifier(item);
@ -447,12 +446,12 @@ describe("ItemHelper", () =>
const itemId = container.resolve<HashUtil>("HashUtil").generate(); const itemId = container.resolve<HashUtil>("HashUtil").generate();
const item: Item = { const item: Item = {
_id: itemId, _id: itemId,
_tpl: "590c657e86f77412b013051d", // "Grizzly medical kit" _tpl: "590c657e86f77412b013051d", // "Grizzly medical kit"
upd: { upd: {
MedKit: { MedKit: {
HpResource: 900 // 1800 total HpResource: 900, // 1800 total
} },
} },
}; };
const result = itemHelper.getItemQualityModifier(item); const result = itemHelper.getItemQualityModifier(item);
@ -460,7 +459,7 @@ describe("ItemHelper", () =>
expect(result).toBe(0.5); expect(result).toBe(0.5);
}); });
it("should return correct value for a reparable helmet", () => it("should return correct value for a repairable helmet", () =>
{ {
const itemId = container.resolve<HashUtil>("HashUtil").generate(); const itemId = container.resolve<HashUtil>("HashUtil").generate();
const item: Item = { const item: Item = {
@ -469,9 +468,9 @@ describe("ItemHelper", () =>
upd: { upd: {
Repairable: { Repairable: {
Durability: 19, Durability: 19,
MaxDurability: 38 MaxDurability: 38,
} },
} },
}; };
const result = itemHelper.getItemQualityModifier(item); const result = itemHelper.getItemQualityModifier(item);
@ -488,9 +487,9 @@ describe("ItemHelper", () =>
upd: { upd: {
Repairable: { Repairable: {
Durability: 20, Durability: 20,
MaxDurability: 100 MaxDurability: 100,
} },
} },
}; };
const result = itemHelper.getItemQualityModifier(item); const result = itemHelper.getItemQualityModifier(item);
@ -506,9 +505,9 @@ describe("ItemHelper", () =>
_tpl: "5448fee04bdc2dbc018b4567", // "Bottle of water (0.6L)" _tpl: "5448fee04bdc2dbc018b4567", // "Bottle of water (0.6L)"
upd: { upd: {
FoodDrink: { FoodDrink: {
HpPercent: 30 // Not actually a percentage, but value of max 60. HpPercent: 30, // Not actually a percentage, but value of max 60.
} },
} },
}; };
const result = itemHelper.getItemQualityModifier(item); const result = itemHelper.getItemQualityModifier(item);
@ -524,9 +523,9 @@ describe("ItemHelper", () =>
_tpl: "5780cf7f2459777de4559322", // "Dorm room 314 marked key" _tpl: "5780cf7f2459777de4559322", // "Dorm room 314 marked key"
upd: { upd: {
Key: { Key: {
NumberOfUsages: 5 NumberOfUsages: 5,
} },
} },
}; };
const result = itemHelper.getItemQualityModifier(item); const result = itemHelper.getItemQualityModifier(item);
@ -543,9 +542,9 @@ describe("ItemHelper", () =>
upd: { upd: {
Resource: { Resource: {
Value: 50, // How much fuel is left in the tank. Value: 50, // How much fuel is left in the tank.
UnitsConsumed: 50 // How much fuel has been used in the generator. UnitsConsumed: 50, // How much fuel has been used in the generator.
} },
} },
}; };
const result = itemHelper.getItemQualityModifier(item); const result = itemHelper.getItemQualityModifier(item);
@ -561,9 +560,9 @@ describe("ItemHelper", () =>
_tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit"
upd: { upd: {
RepairKit: { RepairKit: {
Resource: 600 Resource: 600,
} },
} },
}; };
const result = itemHelper.getItemQualityModifier(item); const result = itemHelper.getItemQualityModifier(item);
@ -579,9 +578,9 @@ describe("ItemHelper", () =>
_tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit"
upd: { upd: {
RepairKit: { RepairKit: {
Resource: 0 Resource: 0,
} },
} },
}; };
const result = itemHelper.getItemQualityModifier(item); const result = itemHelper.getItemQualityModifier(item);
@ -594,14 +593,14 @@ describe("ItemHelper", () =>
{ {
it("should return the correct quality value for armor items", () => it("should return the correct quality value for armor items", () =>
{ {
const armor = itemHelper.getItem("5648a7494bdc2d9d488b4583")[1]; // "PACA Soft Armor" const armor = itemHelper.getItem("5648a7494bdc2d9d488b4583")[1]; // "PACA Soft Armor"
const repairable: Repairable = { const repairable: Repairable = {
Durability: 25, Durability: 25,
MaxDurability: 50 MaxDurability: 50,
}; };
const item: Item = { // Not used for armor, but required for the method. const item: Item = { // Not used for armor, but required for the method.
_id: "", _id: "",
_tpl: "" _tpl: "",
}; };
// Cast the method to any to allow access to private/protected method. // Cast the method to any to allow access to private/protected method.
@ -612,14 +611,14 @@ describe("ItemHelper", () =>
it("should not use the Repairable MaxDurability property for armor", () => it("should not use the Repairable MaxDurability property for armor", () =>
{ {
const armor = itemHelper.getItem("5648a7494bdc2d9d488b4583")[1]; // "PACA Soft Armor" const armor = itemHelper.getItem("5648a7494bdc2d9d488b4583")[1]; // "PACA Soft Armor"
const repairable: Repairable = { const repairable: Repairable = {
Durability: 25, Durability: 25,
MaxDurability: 1000 // This should be ignored. MaxDurability: 1000, // This should be ignored.
}; };
const item: Item = { // Not used for armor, but required for the method. const item: Item = { // Not used for armor, but required for the method.
_id: "", _id: "",
_tpl: "" _tpl: "",
}; };
// Cast the method to any to allow access to private/protected method. // Cast the method to any to allow access to private/protected method.
@ -630,14 +629,14 @@ describe("ItemHelper", () =>
it("should return the correct quality value for weapon items", () => it("should return the correct quality value for weapon items", () =>
{ {
const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun"
const repairable: Repairable = { const repairable: Repairable = {
Durability: 50, Durability: 50,
MaxDurability: 100 MaxDurability: 100,
}; };
const item: Item = { const item: Item = {
_id: "", _id: "",
_tpl: "" _tpl: "",
}; };
// Cast the method to any to allow access to private/protected method. // Cast the method to any to allow access to private/protected method.
@ -648,15 +647,15 @@ describe("ItemHelper", () =>
it("should fall back to using Repairable MaxDurability for weapon items", () => it("should fall back to using Repairable MaxDurability for weapon items", () =>
{ {
const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun"
weapon._props.MaxDurability = undefined; // Remove the MaxDurability property. weapon._props.MaxDurability = undefined; // Remove the MaxDurability property.
const repairable: Repairable = { const repairable: Repairable = {
Durability: 50, Durability: 50,
MaxDurability: 200 // This should be used now. MaxDurability: 200, // This should be used now.
}; };
const item: Item = { const item: Item = {
_id: "", _id: "",
_tpl: "" _tpl: "",
}; };
// Cast the method to any to allow access to private/protected method. // Cast the method to any to allow access to private/protected method.
@ -667,15 +666,15 @@ describe("ItemHelper", () =>
it("should return 1 if durability value is invalid", () => it("should return 1 if durability value is invalid", () =>
{ {
const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun"
weapon._props.MaxDurability = undefined; // Remove the MaxDurability property. weapon._props.MaxDurability = undefined; // Remove the MaxDurability property.
const repairable: Repairable = { const repairable: Repairable = {
Durability: 50, Durability: 50,
MaxDurability: undefined // Remove the MaxDurability property value... Technically an invalid Type. MaxDurability: undefined, // Remove the MaxDurability property value... Technically an invalid Type.
}; };
const item: Item = { const item: Item = {
_id: "", _id: "",
_tpl: "" _tpl: "",
}; };
// Mock the logger's error method to prevent it from being actually called. // Mock the logger's error method to prevent it from being actually called.
@ -691,15 +690,15 @@ describe("ItemHelper", () =>
it("should not divide by zero", () => it("should not divide by zero", () =>
{ {
const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun"
weapon._props.MaxDurability = undefined; // Remove the MaxDurability property. weapon._props.MaxDurability = undefined; // Remove the MaxDurability property.
const repairable: Repairable = { const repairable: Repairable = {
Durability: 50, Durability: 50,
MaxDurability: 0 // This is a problem. MaxDurability: 0, // This is a problem.
}; };
const item: Item = { const item: Item = {
_id: "", _id: "",
_tpl: "" _tpl: "",
}; };
// Cast the method to any to allow access to private/protected method. // Cast the method to any to allow access to private/protected method.
@ -710,15 +709,15 @@ describe("ItemHelper", () =>
it("should log an error if durability is invalid", () => it("should log an error if durability is invalid", () =>
{ {
const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun" const weapon = itemHelper.getItem("5a38e6bac4a2826c6e06d79b")[1]; // "TOZ-106 20ga bolt-action shotgun"
weapon._props.MaxDurability = undefined; // Remove the MaxDurability property. weapon._props.MaxDurability = undefined; // Remove the MaxDurability property.
const repairable: Repairable = { const repairable: Repairable = {
Durability: 50, Durability: 50,
MaxDurability: undefined // Remove the MaxDurability property value... Technically an invalid Type. MaxDurability: undefined, // Remove the MaxDurability property value... Technically an invalid Type.
}; };
const item: Item = { const item: Item = {
_id: "", _id: "",
_tpl: "" _tpl: "",
}; };
const loggerErrorSpy = vi.spyOn((itemHelper as any).logger, "error"); const loggerErrorSpy = vi.spyOn((itemHelper as any).logger, "error");
@ -735,9 +734,9 @@ describe("ItemHelper", () =>
it("should return an array containing only the parent ID when no children are found", () => it("should return an array containing only the parent ID when no children are found", () =>
{ {
const items: Item[] = [ const items: Item[] = [
{ _id: "1", _tpl: "", parentId: null }, {_id: "1", _tpl: "", parentId: null},
{ _id: "2", _tpl: "", parentId: null }, {_id: "2", _tpl: "", parentId: null},
{ _id: "3", _tpl: "", parentId: "2" } {_id: "3", _tpl: "", parentId: "2"},
]; ];
const result = itemHelper.findAndReturnChildrenByItems(items, "1"); const result = itemHelper.findAndReturnChildrenByItems(items, "1");
expect(result).toEqual(["1"]); expect(result).toEqual(["1"]);
@ -746,9 +745,9 @@ describe("ItemHelper", () =>
it("should return array of child IDs when single-level children are found", () => it("should return array of child IDs when single-level children are found", () =>
{ {
const items: Item[] = [ const items: Item[] = [
{ _id: "1", _tpl: "", parentId: null }, {_id: "1", _tpl: "", parentId: null},
{ _id: "2", _tpl: "", parentId: "1" }, {_id: "2", _tpl: "", parentId: "1"},
{ _id: "3", _tpl: "", parentId: "1" } {_id: "3", _tpl: "", parentId: "1"},
]; ];
const result = itemHelper.findAndReturnChildrenByItems(items, "1"); const result = itemHelper.findAndReturnChildrenByItems(items, "1");
expect(result).toEqual(["2", "3", "1"]); expect(result).toEqual(["2", "3", "1"]);
@ -757,10 +756,10 @@ describe("ItemHelper", () =>
it("should return array of child IDs when multi-level children are found", () => it("should return array of child IDs when multi-level children are found", () =>
{ {
const items: Item[] = [ const items: Item[] = [
{ _id: "1", _tpl: "", parentId: null }, {_id: "1", _tpl: "", parentId: null},
{ _id: "2", _tpl: "", parentId: "1" }, {_id: "2", _tpl: "", parentId: "1"},
{ _id: "3", _tpl: "", parentId: "2" }, {_id: "3", _tpl: "", parentId: "2"},
{ _id: "4", _tpl: "", parentId: "3" } {_id: "4", _tpl: "", parentId: "3"},
]; ];
const result = itemHelper.findAndReturnChildrenByItems(items, "1"); const result = itemHelper.findAndReturnChildrenByItems(items, "1");
expect(result).toEqual(["4", "3", "2", "1"]); expect(result).toEqual(["4", "3", "2", "1"]);
@ -769,8 +768,8 @@ describe("ItemHelper", () =>
it("should return an array containing only the parent ID when parent ID does not exist in items", () => it("should return an array containing only the parent ID when parent ID does not exist in items", () =>
{ {
const items: Item[] = [ const items: Item[] = [
{ _id: "1", _tpl: "", parentId: null }, {_id: "1", _tpl: "", parentId: null},
{ _id: "2", _tpl: "", parentId: "1" } {_id: "2", _tpl: "", parentId: "1"},
]; ];
const result = itemHelper.findAndReturnChildrenByItems(items, "3"); const result = itemHelper.findAndReturnChildrenByItems(items, "3");
expect(result).toEqual(["3"]); expect(result).toEqual(["3"]);
@ -785,7 +784,7 @@ describe("ItemHelper", () =>
const item: Item = { const item: Item = {
_id: itemId, _id: itemId,
_tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit"
upd: {} upd: {},
}; };
const result = itemHelper.getItemStackSize(item); const result = itemHelper.getItemStackSize(item);
expect(result).toBe(1); expect(result).toBe(1);
@ -796,7 +795,7 @@ describe("ItemHelper", () =>
const itemId = container.resolve<HashUtil>("HashUtil").generate(); const itemId = container.resolve<HashUtil>("HashUtil").generate();
const item: Item = { const item: Item = {
_id: itemId, _id: itemId,
_tpl: "591094e086f7747caa7bb2ef" // "Body armor repair kit" _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit"
}; };
const result = itemHelper.getItemStackSize(item); const result = itemHelper.getItemStackSize(item);
expect(result).toBe(1); expect(result).toBe(1);
@ -809,8 +808,8 @@ describe("ItemHelper", () =>
_id: itemId, _id: itemId,
_tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit"
upd: { upd: {
StackObjectsCount: 5 StackObjectsCount: 5,
} },
}; };
const result = itemHelper.getItemStackSize(item); const result = itemHelper.getItemStackSize(item);
expect(result).toBe(5); expect(result).toBe(5);
@ -827,8 +826,8 @@ describe("ItemHelper", () =>
_tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit"
upd: { upd: {
BuyRestrictionCurrent: 0, BuyRestrictionCurrent: 0,
BuyRestrictionMax: 1 BuyRestrictionMax: 1,
} },
}; };
const result = itemHelper.hasBuyRestrictions(item); const result = itemHelper.hasBuyRestrictions(item);
expect(result).toBe(true); expect(result).toBe(true);
@ -840,7 +839,7 @@ describe("ItemHelper", () =>
const item: Item = { const item: Item = {
_id: itemId, _id: itemId,
_tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit" _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit"
upd: {} upd: {},
}; };
const result = itemHelper.hasBuyRestrictions(item); const result = itemHelper.hasBuyRestrictions(item);
expect(result).toBe(false); expect(result).toBe(false);
@ -851,7 +850,7 @@ describe("ItemHelper", () =>
const itemId = container.resolve<HashUtil>("HashUtil").generate(); const itemId = container.resolve<HashUtil>("HashUtil").generate();
const item: Item = { const item: Item = {
_id: itemId, _id: itemId,
_tpl: "591094e086f7747caa7bb2ef" // "Body armor repair kit" _tpl: "591094e086f7747caa7bb2ef", // "Body armor repair kit"
}; };
const result = itemHelper.hasBuyRestrictions(item); const result = itemHelper.hasBuyRestrictions(item);
expect(result).toBe(false); expect(result).toBe(false);
@ -881,12 +880,12 @@ describe("ItemHelper", () =>
describe("addCartridgesToAmmoBox", () => describe("addCartridgesToAmmoBox", () =>
{ {
it("should return an array with 1xammoBox and 1xcartridge item", () => it("should return an array with 1x ammoBox and 1x cartridge item", () =>
{ {
const itemId = container.resolve<HashUtil>("HashUtil").generate(); const itemId = container.resolve<HashUtil>("HashUtil").generate();
const ammoBox: Item[] = [{ const ammoBox: Item[] = [{
_id: itemId, _id: itemId,
_tpl: "5c12619186f7743f871c8a32" // "9x39mm SPP gs ammo pack (8 pcs)" _tpl: "5c12619186f7743f871c8a32", // "9x39mm SPP gs ammo pack (8 pcs)"
}]; }];
const databaseServer = container.resolve<DatabaseServer>("DatabaseServer"); const databaseServer = container.resolve<DatabaseServer>("DatabaseServer");
@ -897,12 +896,12 @@ describe("ItemHelper", () =>
expect(ammoBox[1].upd.StackObjectsCount).toBe(8); expect(ammoBox[1].upd.StackObjectsCount).toBe(8);
}); });
it("should return an array with 1xammoBox and 2xcartridge items", () => it("should return an array with 1x ammoBox and 2x cartridge items", () =>
{ {
const itemId = container.resolve<HashUtil>("HashUtil").generate(); const itemId = container.resolve<HashUtil>("HashUtil").generate();
const ammoBox: Item[] = [{ const ammoBox: Item[] = [{
_id: itemId, _id: itemId,
_tpl: "5737292724597765e5728562" // "5.45x39mm BP gs ammo pack (120 pcs)"" _tpl: "5737292724597765e5728562", // "5.45x39mm BP gs ammo pack (120 pcs)""
}]; }];
const databaseServer = container.resolve<DatabaseServer>("DatabaseServer"); const databaseServer = container.resolve<DatabaseServer>("DatabaseServer");
@ -919,7 +918,7 @@ describe("ItemHelper", () =>
const itemId = container.resolve<HashUtil>("HashUtil").generate(); const itemId = container.resolve<HashUtil>("HashUtil").generate();
const ammoBox: Item[] = [{ const ammoBox: Item[] = [{
_id: itemId, _id: itemId,
_tpl: "5737292724597765e5728562" // "5.45x39mm BP gs ammo pack (120 pcs)"" _tpl: "5737292724597765e5728562", // "5.45x39mm BP gs ammo pack (120 pcs)""
}]; }];
const databaseServer = container.resolve<DatabaseServer>("DatabaseServer"); const databaseServer = container.resolve<DatabaseServer>("DatabaseServer");
@ -934,7 +933,7 @@ describe("ItemHelper", () =>
const itemId = container.resolve<HashUtil>("HashUtil").generate(); const itemId = container.resolve<HashUtil>("HashUtil").generate();
const ammoBox: Item[] = [{ const ammoBox: Item[] = [{
_id: itemId, _id: itemId,
_tpl: "5737292724597765e5728562" // "5.45x39mm BP gs ammo pack (120 pcs)"" _tpl: "5737292724597765e5728562", // "5.45x39mm BP gs ammo pack (120 pcs)""
}]; }];
const databaseServer = container.resolve<DatabaseServer>("DatabaseServer"); const databaseServer = container.resolve<DatabaseServer>("DatabaseServer");
@ -1015,8 +1014,8 @@ describe("ItemHelper", () =>
_id: container.resolve<HashUtil>("HashUtil").generate(), _id: container.resolve<HashUtil>("HashUtil").generate(),
_tpl: "59e690b686f7746c9f75e848", // m995 _tpl: "59e690b686f7746c9f75e848", // m995
upd: { upd: {
StackObjectsCount: 80 // Default is 60 StackObjectsCount: 80, // Default is 60
} },
}; };
const result = itemHelper.splitStack(stackableItem); // "Roubles" const result = itemHelper.splitStack(stackableItem); // "Roubles"
@ -1029,8 +1028,8 @@ describe("ItemHelper", () =>
_id: container.resolve<HashUtil>("HashUtil").generate(), _id: container.resolve<HashUtil>("HashUtil").generate(),
_tpl: "59e690b686f7746c9f75e848", // m995 _tpl: "59e690b686f7746c9f75e848", // m995
upd: { upd: {
StackObjectsCount: 80 // Default is 60 StackObjectsCount: 80, // Default is 60
} },
}; };
const result = itemHelper.splitStack(stackableItem); // "Roubles" const result = itemHelper.splitStack(stackableItem); // "Roubles"
const itemCount = result.reduce((sum, curr) => sum + curr.upd.StackObjectsCount, 0); const itemCount = result.reduce((sum, curr) => sum + curr.upd.StackObjectsCount, 0);
@ -1043,8 +1042,8 @@ describe("ItemHelper", () =>
_id: container.resolve<HashUtil>("HashUtil").generate(), _id: container.resolve<HashUtil>("HashUtil").generate(),
_tpl: "59e690b686f7746c9f75e848", // m995 _tpl: "59e690b686f7746c9f75e848", // m995
upd: { upd: {
StackObjectsCount: 60 // Default is 60 StackObjectsCount: 60, // Default is 60
} },
}; };
const result = itemHelper.splitStack(stackableItem); // "Roubles" const result = itemHelper.splitStack(stackableItem); // "Roubles"
const itemCount = result.reduce((sum, curr) => sum + curr.upd.StackObjectsCount, 0); const itemCount = result.reduce((sum, curr) => sum + curr.upd.StackObjectsCount, 0);
@ -1057,7 +1056,7 @@ describe("ItemHelper", () =>
const stackableItem: Item = { const stackableItem: Item = {
_id: container.resolve<HashUtil>("HashUtil").generate(), _id: container.resolve<HashUtil>("HashUtil").generate(),
_tpl: "59e690b686f7746c9f75e848", // m995 _tpl: "59e690b686f7746c9f75e848", // m995
upd: {} upd: {},
}; };
const result = itemHelper.splitStack(stackableItem); // "Roubles" const result = itemHelper.splitStack(stackableItem); // "Roubles"
expect(result.length).toBe(1); expect(result.length).toBe(1);
@ -1067,7 +1066,7 @@ describe("ItemHelper", () =>
{ {
const stackableItem: Item = { const stackableItem: Item = {
_id: container.resolve<HashUtil>("HashUtil").generate(), _id: container.resolve<HashUtil>("HashUtil").generate(),
_tpl: "59e690b686f7746c9f75e848" // m995 _tpl: "59e690b686f7746c9f75e848", // m995
}; };
const result = itemHelper.splitStack(stackableItem); // "Roubles" const result = itemHelper.splitStack(stackableItem); // "Roubles"
expect(result.length).toBe(1); expect(result.length).toBe(1);
@ -1085,7 +1084,7 @@ describe("ItemHelper", () =>
"5736026a245977644601dc61", "5736026a245977644601dc61",
"573603562459776430731618", "573603562459776430731618",
"573603c924597764442bd9cb", "573603c924597764442bd9cb",
"5735fdcd2459776445391d61" "5735fdcd2459776445391d61",
]; ];
const mockTemplateItem = { const mockTemplateItem = {
_id: "571a29dc2459771fb2755a6a", _id: "571a29dc2459771fb2755a6a",
@ -1094,11 +1093,11 @@ describe("ItemHelper", () =>
Cartridges: [{ Cartridges: [{
_props: { _props: {
filters: [{ filters: [{
Filter: validAmmoItems Filter: validAmmoItems,
}] }],
} },
}] }],
} },
}; };
vi.spyOn((itemHelper as any).randomUtil, "getArrayValue").mockReturnValue(validAmmoItems[0]); vi.spyOn((itemHelper as any).randomUtil, "getArrayValue").mockReturnValue(validAmmoItems[0]);
@ -1113,9 +1112,9 @@ describe("ItemHelper", () =>
const fakeTemplateItem = { const fakeTemplateItem = {
_props: { _props: {
Cartridges: [ Cartridges: [
{} {},
] ],
} },
}; };
const result = itemHelper.getRandomCompatibleCaliberTemplateId(fakeTemplateItem as ITemplateItem); const result = itemHelper.getRandomCompatibleCaliberTemplateId(fakeTemplateItem as ITemplateItem);

View File

@ -1,8 +1,8 @@
/* eslint-disable @typescript-eslint/naming-convention */ /* eslint-disable @typescript-eslint/naming-convention */
import "reflect-metadata"; import "reflect-metadata";
import { container } from "tsyringe";
import { vi, beforeEach, afterEach, describe, expect, it } from "vitest";
import { ItemBaseClassService } from "@spt-aki/services/ItemBaseClassService"; import { ItemBaseClassService } from "@spt-aki/services/ItemBaseClassService";
import { container } from "tsyringe";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
describe("ItemBaseClassService", () => describe("ItemBaseClassService", () =>
{ {
@ -64,7 +64,10 @@ describe("ItemBaseClassService", () =>
// Remove item from base cache // Remove item from base cache
delete itemBaseClassService.itemBaseClassesCache[salewaTpl]; delete itemBaseClassService.itemBaseClassesCache[salewaTpl];
const result = itemBaseClassService.itemHasBaseClass(salewaTpl, ["543be5664bdc2dd4348b4569", "54009119af1c881c07000029"]); // "Meds" and "Item" type const result = itemBaseClassService.itemHasBaseClass(salewaTpl, [
"543be5664bdc2dd4348b4569",
"54009119af1c881c07000029",
]); // "Meds" and "Item" type
expect(result).toBe(true); expect(result).toBe(true);
}); });

View File

@ -1,16 +1,16 @@
/* eslint-disable @typescript-eslint/naming-convention */ /* eslint-disable @typescript-eslint/naming-convention */
import "reflect-metadata"; import "reflect-metadata";
import { container } from "tsyringe"; import { container } from "tsyringe";
import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { PaymentService } from "@spt-aki/services/PaymentService"; import { PaymentService } from "@spt-aki/services/PaymentService";
import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { IPmcData } from "@spt-aki/models/eft/common/IPmcData";
import { IProcessBuyTradeRequestData } from "@spt-aki/models/eft/trade/IProcessBuyTradeRequestData";
import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse";
import { HashUtil } from "@spt-aki/utils/HashUtil";
import { ITraderBase } from "@spt-aki/models/eft/common/tables/ITrader";
import { Item } from "@spt-aki/models/eft/common/tables/IItem"; import { Item } from "@spt-aki/models/eft/common/tables/IItem";
import { ITraderBase } from "@spt-aki/models/eft/common/tables/ITrader";
import { IItemEventRouterResponse } from "@spt-aki/models/eft/itemEvent/IItemEventRouterResponse";
import { IProcessBuyTradeRequestData } from "@spt-aki/models/eft/trade/IProcessBuyTradeRequestData";
import { HashUtil } from "@spt-aki/utils/HashUtil";
describe("PaymentService", () => describe("PaymentService", () =>
{ {
@ -44,8 +44,8 @@ describe("PaymentService", () =>
_id: costItemId, _id: costItemId,
_tpl: costItemTpl, _tpl: costItemTpl,
upd: { upd: {
StackObjectsCount: costAmount * 4 // More than enough. StackObjectsCount: costAmount * 4, // More than enough.
} },
} as Item; } as Item;
// Object representing the player's PMC inventory. // Object representing the player's PMC inventory.
@ -54,12 +54,12 @@ describe("PaymentService", () =>
[traderId]: { [traderId]: {
salesSum: 0, salesSum: 0,
unlocked: true, unlocked: true,
disabled: false disabled: false,
} },
}, },
Inventory: { Inventory: {
items: [moneyItem] items: [moneyItem],
} },
} as unknown as IPmcData; } as unknown as IPmcData;
// Buy a factory map from Therapist... although it doesn't really matter what the item is as there's no // Buy a factory map from Therapist... although it doesn't really matter what the item is as there's no
@ -74,9 +74,9 @@ describe("PaymentService", () =>
scheme_items: [ scheme_items: [
{ {
id: costItemId, id: costItemId,
count: costAmount count: costAmount,
} },
] ],
} as IProcessBuyTradeRequestData; } as IProcessBuyTradeRequestData;
// Inconsequential profile ID // Inconsequential profile ID
@ -90,10 +90,10 @@ describe("PaymentService", () =>
items: { items: {
new: [], new: [],
change: [], change: [],
del: [] del: [],
} },
} },
} },
} as unknown as IItemEventRouterResponse; } as unknown as IItemEventRouterResponse;
// Mock the logger debug method to return void. // Mock the logger debug method to return void.
@ -101,13 +101,14 @@ describe("PaymentService", () =>
{}); {});
// Mock the trader helper to return a trader with the currency of Roubles. // Mock the trader helper to return a trader with the currency of Roubles.
const traderHelperGetTraderSpy = vi.spyOn((paymentService as any).traderHelper, "getTrader").mockReturnValue({ const traderHelperGetTraderSpy = vi.spyOn((paymentService as any).traderHelper, "getTrader")
tid: traderId, .mockReturnValue({
currency: "RUB" tid: traderId,
} as unknown as ITraderBase); currency: "RUB",
} as unknown as ITraderBase);
// Mock the addPaymentToOutput method to subtract the item cost from the money stack. // Mock the addPaymentToOutput method to subtract the item cost from the money stack.
const addPaymentToOutputSpy = vi.spyOn((paymentService as any), "addPaymentToOutput").mockImplementation(() => const addPaymentToOutputSpy = vi.spyOn(paymentService as any, "addPaymentToOutput").mockImplementation(() =>
{ {
moneyItem.upd.StackObjectsCount -= costAmount; moneyItem.upd.StackObjectsCount -= costAmount;
return { return {
@ -115,18 +116,25 @@ describe("PaymentService", () =>
profileChanges: { profileChanges: {
[sessionID]: { [sessionID]: {
items: { items: {
change: [moneyItem] change: [moneyItem],
} },
} },
} },
}; };
}); });
// Mock the traderHelper lvlUp method to return void. // Mock the traderHelper lvlUp method to return void.
const traderHelperLvlUpSpy = vi.spyOn((paymentService as any).traderHelper, "lvlUp").mockImplementation(() => const traderHelperLvlUpSpy = vi.spyOn((paymentService as any).traderHelper, "lvlUp").mockImplementation(
{}); () =>
{},
);
const output = paymentService.payMoney(pmcData, processBuyTradeRequestData, sessionID, itemEventRouterResponse); const output = paymentService.payMoney(
pmcData,
processBuyTradeRequestData,
sessionID,
itemEventRouterResponse,
);
// Check for absence of output warnings. // Check for absence of output warnings.
expect(output.warnings).toHaveLength(0); expect(output.warnings).toHaveLength(0);
@ -139,7 +147,13 @@ describe("PaymentService", () =>
// Check if mocked methods were called as expected. // Check if mocked methods were called as expected.
expect(traderHelperGetTraderSpy).toBeCalledTimes(1); expect(traderHelperGetTraderSpy).toBeCalledTimes(1);
expect(addPaymentToOutputSpy).toBeCalledWith(expect.anything(), costItemTpl, costAmount, sessionID, expect.anything()); expect(addPaymentToOutputSpy).toBeCalledWith(
expect.anything(),
costItemTpl,
costAmount,
sessionID,
expect.anything(),
);
expect(traderHelperLvlUpSpy).toBeCalledTimes(1); expect(traderHelperLvlUpSpy).toBeCalledTimes(1);
}); });
}); });
@ -151,14 +165,14 @@ describe("PaymentService", () =>
const hashUtil = container.resolve<HashUtil>("HashUtil"); const hashUtil = container.resolve<HashUtil>("HashUtil");
const stashItem: Item = { const stashItem: Item = {
_id: "stashid", _id: "stashid",
_tpl: "55d7217a4bdc2d86028b456d" // standard stash id _tpl: "55d7217a4bdc2d86028b456d", // standard stash id
}; };
const inventoryItemToFind: Item = { const inventoryItemToFind: Item = {
_id: hashUtil.generate(), _id: hashUtil.generate(),
_tpl: "544fb6cc4bdc2d34748b456e", // Slickers chocolate bar _tpl: "544fb6cc4bdc2d34748b456e", // Slickers chocolate bar
parentId: stashItem._id, parentId: stashItem._id,
slotId: "hideout" slotId: "hideout",
}; };
const playerInventory = [stashItem, inventoryItemToFind]; const playerInventory = [stashItem, inventoryItemToFind];
@ -172,20 +186,20 @@ describe("PaymentService", () =>
const hashUtil = container.resolve<HashUtil>("HashUtil"); const hashUtil = container.resolve<HashUtil>("HashUtil");
const stashItem: Item = { const stashItem: Item = {
_id: "stashId", _id: "stashId",
_tpl: "55d7217a4bdc2d86028b456d" // standard stash id _tpl: "55d7217a4bdc2d86028b456d", // standard stash id
}; };
const foodBagToHoldItemToFind: Item = { const foodBagToHoldItemToFind: Item = {
_id: hashUtil.generate(), _id: hashUtil.generate(),
_tpl: "5c093db286f7740a1b2617e3", _tpl: "5c093db286f7740a1b2617e3",
parentId: stashItem._id, parentId: stashItem._id,
slotId: "hideout" slotId: "hideout",
}; };
const inventoryItemToFind: Item = { const inventoryItemToFind: Item = {
_id: hashUtil.generate(), _id: hashUtil.generate(),
_tpl: "544fb6cc4bdc2d34748b456e", // Slickers chocolate bar _tpl: "544fb6cc4bdc2d34748b456e", // Slickers chocolate bar
parentId: foodBagToHoldItemToFind._id parentId: foodBagToHoldItemToFind._id,
}; };
const playerInventory = [stashItem, foodBagToHoldItemToFind, inventoryItemToFind]; const playerInventory = [stashItem, foodBagToHoldItemToFind, inventoryItemToFind];
@ -199,14 +213,14 @@ describe("PaymentService", () =>
const hashUtil = container.resolve<HashUtil>("HashUtil"); const hashUtil = container.resolve<HashUtil>("HashUtil");
const stashItem: Item = { const stashItem: Item = {
_id: "stashId", _id: "stashId",
_tpl: "55d7217a4bdc2d86028b456d" // standard stash id _tpl: "55d7217a4bdc2d86028b456d", // standard stash id
}; };
const inventoryItemToFind: Item = { const inventoryItemToFind: Item = {
_id: hashUtil.generate(), _id: hashUtil.generate(),
_tpl: "544fb6cc4bdc2d34748b456e", // Slickers chocolate bar _tpl: "544fb6cc4bdc2d34748b456e", // Slickers chocolate bar
parentId: stashItem._id, parentId: stashItem._id,
slotId: "hideout" slotId: "hideout",
}; };
const playerInventory = [stashItem, inventoryItemToFind]; const playerInventory = [stashItem, inventoryItemToFind];
@ -220,16 +234,16 @@ describe("PaymentService", () =>
const hashUtil = container.resolve<HashUtil>("HashUtil"); const hashUtil = container.resolve<HashUtil>("HashUtil");
const stashItem: Item = { const stashItem: Item = {
_id: "stashId", _id: "stashId",
_tpl: "55d7217a4bdc2d86028b456d" // standard stash id _tpl: "55d7217a4bdc2d86028b456d", // standard stash id
}; };
const inventoryItemToFind: Item = { const inventoryItemToFind: Item = {
_id: hashUtil.generate(), _id: hashUtil.generate(),
_tpl: "544fb6cc4bdc2d34748b456e", // Slickers chocolate bar _tpl: "544fb6cc4bdc2d34748b456e", // Slickers chocolate bar
parentId: stashItem._id, parentId: stashItem._id,
slotId: "hideout" slotId: "hideout",
}; };
const playerInventory = [ inventoryItemToFind]; const playerInventory = [inventoryItemToFind];
const result = paymentService.isInStash("notCorrectId", playerInventory, stashItem._id); const result = paymentService.isInStash("notCorrectId", playerInventory, stashItem._id);

View File

@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/naming-convention */ /* eslint-disable @typescript-eslint/naming-convention */
import "reflect-metadata"; import "reflect-metadata";
import { container } from "tsyringe"; import { container } from "tsyringe";
import { vi, beforeEach, afterEach, describe, expect, it } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { IPmcData } from "@spt-aki/models/eft/common/IPmcData"; import { IPmcData } from "@spt-aki/models/eft/common/IPmcData";
import { PlayerService } from "@spt-aki/services/PlayerService"; import { PlayerService } from "@spt-aki/services/PlayerService";
@ -26,8 +26,8 @@ describe("PlayerService", () =>
{ {
const playerProfile = { const playerProfile = {
Info: { Info: {
Experience: 0 // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels Experience: 0, // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels
} },
}; };
const result = playerService.calculateLevel(playerProfile as IPmcData); const result = playerService.calculateLevel(playerProfile as IPmcData);
@ -39,8 +39,8 @@ describe("PlayerService", () =>
{ {
const playerProfile = { const playerProfile = {
Info: { Info: {
Experience: 999 // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels Experience: 999, // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels
} },
}; };
const result = playerService.calculateLevel(playerProfile as IPmcData); const result = playerService.calculateLevel(playerProfile as IPmcData);
@ -52,8 +52,8 @@ describe("PlayerService", () =>
{ {
const playerProfile = { const playerProfile = {
Info: { Info: {
Experience: 609066 // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels Experience: 609066, // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels
} },
}; };
const result = playerService.calculateLevel(playerProfile as IPmcData); const result = playerService.calculateLevel(playerProfile as IPmcData);
@ -65,8 +65,8 @@ describe("PlayerService", () =>
{ {
const playerProfile = { const playerProfile = {
Info: { Info: {
Experience: 68206066 // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels Experience: 68206066, // Via wiki: https://escapefromtarkov.fandom.com/wiki/Character_skills#Levels
} },
}; };
const result = playerService.calculateLevel(playerProfile as IPmcData); const result = playerService.calculateLevel(playerProfile as IPmcData);

View File

@ -1,6 +1,6 @@
import "reflect-metadata"; import "reflect-metadata";
import { container } from "tsyringe"; import { container } from "tsyringe";
import { vi, afterEach, describe, expect, it, beforeEach } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TimeUtil } from "@spt-aki/utils/TimeUtil"; import { TimeUtil } from "@spt-aki/utils/TimeUtil";