Migrated from Jest to Vitest

Basically the same, except it plays nicer with Typescript and ESM.

I have it mostly working, except for a type error:
`TypeError: Int32Array is not a constructor`

But I'm too damn tired it debug it at the moment.
This commit is contained in:
Refringe 2023-10-27 23:55:34 -04:00 committed by TheSparta
parent 00ac9e190a
commit ad5e0815b6
9 changed files with 498 additions and 498 deletions

View File

@ -9,5 +9,12 @@
"editor.detectIndentation": false,
"editor.tabSize": 4,
"editor.insertSpaces": true
}
},
"cSpell.words": [
"Baseclass",
"IIIA",
"medkit",
"Superfors",
"ULACH"
]
}

View File

@ -1,15 +0,0 @@
/* eslint-disable @typescript-eslint/naming-convention */
import type { Config } from "jest";
import fs from "fs";
const config: Config = {
testEnvironment: "./tests/CustomEnvironment.ts",
roots: [
"./tests/"
],
transform: {
"^.+\\.ts$": [ "@swc/jest", JSON.parse(fs.readFileSync(`${__dirname}/.swcrc`, "utf-8")) ]
}
};
export default config;

View File

@ -14,8 +14,9 @@
"check:circular": "madge --circular --extensions ts ./src/",
"lint": "rome ci src --formatter-enabled=false --max-diagnostics=200",
"lint:fix": "eslint --fix --ext .ts src/**",
"test": "jest --colors --runInBand",
"test:coverage": "jest --coverage --maxWorkers=1 --no-cache",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"build:release": "cross-env PKG_CACHE_PATH=\"./.pkg-cache\" gulp build:release",
"build:debug": "cross-env PKG_CACHE_PATH=\"./.pkg-cache\" gulp build:debug",
"build:bleeding": "cross-env PKG_CACHE_PATH=\"./.pkg-cache\" gulp build:bleeding",
@ -44,27 +45,22 @@
"devDependencies": {
"@babel/preset-env": "7.23.2",
"@babel/preset-typescript": "7.23.2",
"@jest/environment": "^29.7.0",
"@jest/globals": "29.7.0",
"@pnpm/exe": "8.9.0",
"@swc/cli": "0.1.62",
"@swc/core": "1.3.92",
"@swc/jest": "0.2.29",
"@types/i18n": "0.13.7",
"@types/jest": "29.5.5",
"@types/node": "18.18.4",
"@types/proper-lockfile": "4.1.2",
"@types/semver": "7.5.3",
"@types/ws": "8.5.7",
"@typescript-eslint/eslint-plugin": "6.7.5",
"@typescript-eslint/parser": "6.7.5",
"c8": "^8.0.1",
"cross-env": "7.0.3",
"eslint": "8.51.0",
"gulp": "4.0.2",
"gulp-execa": "5.0.1",
"gulp-rename": "2.0.0",
"jest": "29.7.0",
"jest-environment-node": "^29.7.0",
"madge": "6.1.0",
"pkg": "5.8.1",
"pkg-fetch": "3.5.2",
@ -73,7 +69,8 @@
"ts-node-dev": "2.0.0",
"tsconfig-paths": "4.2.0",
"typedoc": "0.25.2",
"typemoq": "2.1.0"
"typemoq": "2.1.0",
"vitest": "1.0.0-beta.3"
},
"overrides": {
"pkg": {

View File

@ -248,70 +248,63 @@ import { Watermark, WatermarkLocale } from "@spt-aki/utils/Watermark";
import { WinstonMainLogger } from "@spt-aki/utils/logging/WinstonMainLogger";
import { WinstonRequestLogger } from "@spt-aki/utils/logging/WinstonRequestLogger";
// For the Jest Custom Environment.
import NodeEnvironment from "jest-environment-node";
import type { EnvironmentContext, JestEnvironmentConfig } from "@jest/environment";
// For the Vitest Custom Environment.
import type { Environment } from "vitest";
import { populateGlobal } from "vitest/environments";
// Used for importing the database.
import path from "path";
import { IDatabaseTables } from "@spt-aki/models/spt/server/IDatabaseTables";
export default class CustomEnvironment extends NodeEnvironment
export default <Environment> {
name: "spt-aki-server",
transformMode: "ssr",
async setup()
{
private container: DependencyContainer;
// For importing the database.
private importerUtil: ImporterUtil;
private databaseServer: DatabaseServer;
constructor(config: JestEnvironmentConfig, context: EnvironmentContext)
{
super(config, context);
this.container = this.register(container);
}
async setup(): Promise<void>
{
await super.setup();
// Register all of the things!
register(container);
// Import the database.
await this.importDatabase();
await importDatabase(container);
// Make the container accessible to the tests.
this.global.container = this.container;
// Populate the global scope with all of the things!
populateGlobal(global, { container }, { bindFunctions: true });
// TODO: Create test account/profile
}
async teardown(): Promise<void>
return {
teardown()
{
// TODO: Delete test account/profile
// Not sure this is required, but it's here just in case.
delete global.container;
await super.teardown();
// TODO: Delete test account/profile
}
};
}
};
// Register all of the things!
private register(container: DependencyContainer): DependencyContainer
function register(container: DependencyContainer): DependencyContainer
{
container.register("ApplicationContext", ApplicationContext, { lifecycle: Lifecycle.Singleton });
this.registerUtils(container);
this.registerRouters(container);
this.registerGenerators(container);
this.registerHelpers(container);
this.registerLoaders(container);
this.registerCallbacks(container);
this.registerServers(container);
this.registerServices(container);
this.registerControllers(container);
registerUtils(container);
registerRouters(container);
registerGenerators(container);
registerHelpers(container);
registerLoaders(container);
registerCallbacks(container);
registerServers(container);
registerServices(container);
registerControllers(container);
this.registerListTypes(container);
registerListTypes(container);
return container;
}
private registerUtils(container: DependencyContainer): void
function registerUtils(container: DependencyContainer): void
{
// Utils
container.register<App>("App", App, { lifecycle: Lifecycle.Singleton });
@ -328,8 +321,11 @@ export default class CustomEnvironment extends NodeEnvironment
container.register<RandomUtil>("RandomUtil", RandomUtil, { lifecycle: Lifecycle.Singleton });
container.register<TimeUtil>("TimeUtil", TimeUtil, { lifecycle: Lifecycle.Singleton });
container.register<VFS>("VFS", VFS, { lifecycle: Lifecycle.Singleton });
// These two trouble-makers are manually mocked, as the original implementation hijacks our test console.
container.register<WatermarkLocale>("WatermarkLocale", WatermarkLocale, { lifecycle: Lifecycle.Singleton });
container.register<Watermark>("Watermark", Watermark, { lifecycle: Lifecycle.Singleton });
container.register<IAsyncQueue>("AsyncQueue", AsyncQueue, { lifecycle: Lifecycle.Singleton });
container.register<IUUidGenerator>("UUidGenerator", UUidGenerator, { lifecycle: Lifecycle.Singleton });
container.register<HttpFileUtil>("HttpFileUtil", HttpFileUtil, { lifecycle: Lifecycle.Singleton });
@ -337,7 +333,7 @@ export default class CustomEnvironment extends NodeEnvironment
container.register<ModTypeCheck>("ModTypeCheck", ModTypeCheck, { lifecycle: Lifecycle.Singleton });
}
private registerRouters(container: DependencyContainer): void
function registerRouters(container: DependencyContainer): void
{
// Routers
container.register<HttpRouter>("HttpRouter", HttpRouter, { lifecycle: Lifecycle.Singleton });
@ -405,7 +401,7 @@ export default class CustomEnvironment extends NodeEnvironment
container.register<WeatherStaticRouter>("WeatherStaticRouter", { useClass: WeatherStaticRouter });
}
private registerGenerators(container: DependencyContainer): void
function registerGenerators(container: DependencyContainer): void
{
// Generators
container.register<BotGenerator>("BotGenerator", BotGenerator);
@ -435,7 +431,7 @@ export default class CustomEnvironment extends NodeEnvironment
container.registerType("InventoryMagGen", "UbglExternalMagGen");
}
private registerHelpers(container: DependencyContainer): void
function registerHelpers(container: DependencyContainer): void
{
// Helpers
container.register<AssortHelper>("AssortHelper", { useClass: AssortHelper });
@ -477,7 +473,7 @@ export default class CustomEnvironment extends NodeEnvironment
container.register<RepeatableQuestHelper>("RepeatableQuestHelper", { useClass: RepeatableQuestHelper });
}
private registerLoaders(container: DependencyContainer): void
function registerLoaders(container: DependencyContainer): void
{
// Loaders
container.register<BundleLoader>("BundleLoader", BundleLoader, { lifecycle: Lifecycle.Singleton });
@ -485,7 +481,7 @@ export default class CustomEnvironment extends NodeEnvironment
container.register<PostAkiModLoader>("PostAkiModLoader", PostAkiModLoader, { lifecycle: Lifecycle.Singleton });
}
private registerCallbacks(container: DependencyContainer): void
function registerCallbacks(container: DependencyContainer): void
{
// Callbacks
container.register<BotCallbacks>("BotCallbacks", { useClass: BotCallbacks });
@ -523,7 +519,7 @@ export default class CustomEnvironment extends NodeEnvironment
container.register<WishlistCallbacks>("WishlistCallbacks", { useClass: WishlistCallbacks });
}
private registerServices(container: DependencyContainer): void
function registerServices(container: DependencyContainer): void
{
// Services
container.register<ImageRouteService>("ImageRouteService", ImageRouteService, { lifecycle: Lifecycle.Singleton });
@ -565,7 +561,7 @@ export default class CustomEnvironment extends NodeEnvironment
container.register<MailSendService>("MailSendService", MailSendService);
}
private registerServers(container: DependencyContainer): void
function registerServers(container: DependencyContainer): void
{
// Servers
container.register<DatabaseServer>("DatabaseServer", DatabaseServer, { lifecycle: Lifecycle.Singleton });
@ -577,7 +573,7 @@ export default class CustomEnvironment extends NodeEnvironment
container.register<HttpBufferHandler>("HttpBufferHandler", HttpBufferHandler, {lifecycle: Lifecycle.Singleton});
}
private registerControllers(container: DependencyContainer): void
function registerControllers(container: DependencyContainer): void
{
// Controllers
container.register<BotController>("BotController", { useClass: BotController });
@ -609,7 +605,7 @@ export default class CustomEnvironment extends NodeEnvironment
container.register<WishlistController>("WishlistController", WishlistController);
}
private registerListTypes(container: DependencyContainer): void
function registerListTypes(container: DependencyContainer): void
{
container.register("OnLoadModService", { useValue: new OnLoadModService(container) });
container.register("HttpListenerModService", { useValue: new HttpListenerModService(container) });
@ -685,23 +681,21 @@ export default class CustomEnvironment extends NodeEnvironment
container.registerType("Serializer", "BundleSerializer");
container.registerType("Serializer", "NotifySerializer");
// Registering these starts the server...?
container.registerType("SaveLoadRouter", "HealthSaveLoadRouter");
container.registerType("SaveLoadRouter", "InraidSaveLoadRouter");
container.registerType("SaveLoadRouter", "InsuranceSaveLoadRouter");
container.registerType("SaveLoadRouter", "ProfileSaveLoadRouter");
}
private async importDatabase(): Promise<void>
async function importDatabase(container: DependencyContainer): Promise<void>
{
this.importerUtil = this.container.resolve<ImporterUtil>("ImporterUtil");
this.databaseServer = this.container.resolve<DatabaseServer>("DatabaseServer");
const importerUtil = container.resolve<ImporterUtil>("ImporterUtil");
const databaseServer = container.resolve<DatabaseServer>("DatabaseServer");
// Read the data from the JSON files.
const databaseDir = path.resolve("./assets/database");
const dataToImport = await this.importerUtil.loadAsync<IDatabaseTables>(`${databaseDir}/`);
const dataToImport = await importerUtil.loadAsync<IDatabaseTables>(`${databaseDir}/`);
// Save the data to memory.
this.databaseServer.setTables(dataToImport);
}
databaseServer.setTables(dataToImport);
}

View File

@ -1,5 +1,7 @@
import "reflect-metadata";
import { vi, beforeAll, afterEach, describe, expect, it } from "vitest";
import { ItemHelper } from "@spt-aki/helpers/ItemHelper";
import { DependencyContainer } from "tsyringe";
import { Item, Repairable } from "@spt-aki/models/eft/common/tables/IItem";
@ -11,22 +13,15 @@ describe("ItemHelper", () =>
let container: DependencyContainer;
let itemHelper: ItemHelper;
// Spies
let handbookHelperGetTemplatePriceSpy: jest.SpyInstance;
let loggerWarningSpy: jest.SpyInstance;
let loggerErrorSpy: jest.SpyInstance;
let databaseServerGetTablesSpy: jest.SpyInstance;
let jsonUtilCloneSpy: jest.SpyInstance;
beforeAll(() =>
{
container = globalThis.container;
container = global.container;
itemHelper = container.resolve<ItemHelper>("ItemHelper");
});
afterEach(() =>
{
jest.restoreAllMocks();
vi.restoreAllMocks();
});
describe("isValidItem", () =>
@ -52,7 +47,7 @@ describe("ItemHelper", () =>
it("should return false when item's price is zero", () =>
{
// Unsure if any item has price of "0", so mock the getItemPrice method to return 0.
jest.spyOn(itemHelper, "getItemPrice").mockReturnValue(0);
vi.spyOn(itemHelper, "getItemPrice").mockReturnValue(0);
const result = itemHelper.isValidItem("5fc64ea372b0dd78d51159dc");
expect(result).toBe(false);
@ -112,7 +107,7 @@ describe("ItemHelper", () =>
const staticPrice = 1;
const tpl = "590c657e86f77412b013051d";
jest.spyOn(itemHelper, "getStaticItemPrice").mockReturnValue(staticPrice);
vi.spyOn(itemHelper, "getStaticItemPrice").mockReturnValue(staticPrice);
const result = itemHelper.getItemPrice(tpl);
@ -125,8 +120,8 @@ describe("ItemHelper", () =>
const dynamicPrice = 42069;
const tpl = "590c657e86f77412b013051d";
jest.spyOn(itemHelper, "getStaticItemPrice").mockReturnValue(staticPrice);
jest.spyOn(itemHelper, "getDynamicItemPrice").mockReturnValue(dynamicPrice);
vi.spyOn(itemHelper, "getStaticItemPrice").mockReturnValue(staticPrice);
vi.spyOn(itemHelper, "getDynamicItemPrice").mockReturnValue(dynamicPrice);
const result = itemHelper.getItemPrice(tpl);
@ -138,8 +133,8 @@ describe("ItemHelper", () =>
{
const tpl = "590c657e86f77412b013051d";
jest.spyOn(itemHelper, "getStaticItemPrice").mockReturnValue(0);
jest.spyOn(itemHelper, "getDynamicItemPrice").mockReturnValue(0);
vi.spyOn(itemHelper, "getStaticItemPrice").mockReturnValue(0);
vi.spyOn(itemHelper, "getDynamicItemPrice").mockReturnValue(0);
const result = itemHelper.getItemPrice(tpl);
@ -156,8 +151,8 @@ describe("ItemHelper", () =>
const dynamicPrice = 69;
const tpl = "590c657e86f77412b013051d";
jest.spyOn(itemHelper, "getStaticItemPrice").mockReturnValue(staticPrice);
jest.spyOn(itemHelper, "getDynamicItemPrice").mockReturnValue(dynamicPrice);
vi.spyOn(itemHelper, "getStaticItemPrice").mockReturnValue(staticPrice);
vi.spyOn(itemHelper, "getDynamicItemPrice").mockReturnValue(dynamicPrice);
const result = itemHelper.getItemMaxPrice(tpl);
@ -170,8 +165,8 @@ describe("ItemHelper", () =>
const dynamicPrice = 420;
const tpl = "590c657e86f77412b013051d";
jest.spyOn(itemHelper, "getStaticItemPrice").mockReturnValue(staticPrice);
jest.spyOn(itemHelper, "getDynamicItemPrice").mockReturnValue(dynamicPrice);
vi.spyOn(itemHelper, "getStaticItemPrice").mockReturnValue(staticPrice);
vi.spyOn(itemHelper, "getDynamicItemPrice").mockReturnValue(dynamicPrice);
const result = itemHelper.getItemMaxPrice(tpl);
@ -183,8 +178,8 @@ describe("ItemHelper", () =>
const price = 42069;
const tpl = "590c657e86f77412b013051d";
jest.spyOn(itemHelper, "getStaticItemPrice").mockReturnValue(price);
jest.spyOn(itemHelper, "getDynamicItemPrice").mockReturnValue(price);
vi.spyOn(itemHelper, "getStaticItemPrice").mockReturnValue(price);
vi.spyOn(itemHelper, "getDynamicItemPrice").mockReturnValue(price);
const result = itemHelper.getItemMaxPrice(tpl);
@ -209,7 +204,7 @@ describe("ItemHelper", () =>
const price = 42069;
const tpl = "590c657e86f77412b013051d";
handbookHelperGetTemplatePriceSpy = jest.spyOn((itemHelper as any).handbookHelper, "getTemplatePrice");
const handbookHelperGetTemplatePriceSpy = vi.spyOn((itemHelper as any).handbookHelper, "getTemplatePrice");
handbookHelperGetTemplatePriceSpy.mockReturnValue(price);
const result = itemHelper.getStaticItemPrice(tpl);
@ -222,7 +217,7 @@ describe("ItemHelper", () =>
const price = 0;
const tpl = "590c657e86f77412b013051d"; // "Grizzly medical kit"
handbookHelperGetTemplatePriceSpy = jest.spyOn((itemHelper as any).handbookHelper, "getTemplatePrice");
const handbookHelperGetTemplatePriceSpy = vi.spyOn((itemHelper as any).handbookHelper, "getTemplatePrice");
handbookHelperGetTemplatePriceSpy.mockReturnValue(price);
const result = itemHelper.getStaticItemPrice(tpl);
@ -320,7 +315,7 @@ describe("ItemHelper", () =>
const parentId = container.resolve<HashUtil>("HashUtil").generate();
loggerWarningSpy = jest.spyOn((itemHelper as any).logger, "warning");
const loggerWarningSpy = vi.spyOn((itemHelper as any).logger, "warning");
itemHelper.generateItemsFromStackSlot(ammoBox[1], parentId);
@ -332,8 +327,8 @@ describe("ItemHelper", () =>
{
it("should call databaseServer.getTables() and jsonUtil.clone() methods", () =>
{
databaseServerGetTablesSpy = jest.spyOn((itemHelper as any).databaseServer, "getTables");
jsonUtilCloneSpy = jest.spyOn((itemHelper as any).jsonUtil, "clone");
const databaseServerGetTablesSpy = vi.spyOn((itemHelper as any).databaseServer, "getTables");
const jsonUtilCloneSpy = vi.spyOn((itemHelper as any).jsonUtil, "clone");
itemHelper.getItems();
@ -404,7 +399,7 @@ describe("ItemHelper", () =>
it("should call getItem with the provided tpl", () =>
{
const itemHelperSpy = jest.spyOn(itemHelper, "getItem");
const itemHelperSpy = vi.spyOn(itemHelper, "getItem");
const tpl = "590c657e86f77412b013051d"; // "Grizzly medical kit"
@ -717,7 +712,7 @@ describe("ItemHelper", () =>
_tpl: ""
};
loggerErrorSpy = jest.spyOn((itemHelper as any).logger, "error");
const loggerErrorSpy = vi.spyOn((itemHelper as any).logger, "error");
// Cast the method to any to allow access to private/protected method.
(itemHelper as any).getRepairableItemQualityValue(weapon, repairable, item);

View File

@ -1,6 +1,8 @@
import "reflect-metadata";
import { DependencyContainer } from "tsyringe";
import { vi, beforeAll, afterEach, describe, expect, it } from "vitest";
import { DependencyContainer } from "tsyringe";
import { PaymentService } from "@spt-aki/services/PaymentService";
describe("PaymentService", () =>
@ -10,13 +12,13 @@ describe("PaymentService", () =>
beforeAll(() =>
{
container = globalThis.container;
container = global.container;
paymentService = container.resolve<PaymentService>("PaymentService");
});
afterEach(() =>
{
jest.restoreAllMocks();
vi.restoreAllMocks();
});
describe("should be registered", () =>

View File

@ -8,6 +8,9 @@
"paths": {
"@spt-aki/*": [
"src/*"
],
"@tests/*": [
"tests/*"
]
}
},

View File

@ -4,7 +4,8 @@
"outDir": "obj",
"declaration": true,
"sourceMap": true,
"noImplicitAny": false
"noImplicitAny": false,
"types": ["vitest/globals"],
},
"include": [
"./types/**/*",

16
project/vitest.config.ts Normal file
View File

@ -0,0 +1,16 @@
/* eslint-disable @typescript-eslint/naming-convention */
import path from "path";
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
name: "spt-server",
root: "./tests",
environment: "./CustomEnvironment.ts",
globals: true,
alias: {
"@spt-aki": path.resolve(__dirname, "src"),
"@tests": path.resolve(__dirname, "tests")
}
}
});