rbxts-transformer-jest
v0.0.2
Published
A Jest transformer for Roblox TypeScript (rbxts) projects.
Maintainers
Readme
rbxts-transformer-jest
TypeScript custom transformer for roblox-ts that hoists jest.mock() and
jest.unmock() calls above imports at compile time.
The Problem
Jest requires jest.mock() calls to execute before the modules they target
are imported. You could manually place mocks above imports, but that's tedious
and easy to forget. Without Babel in the roblox-ts pipeline, there's no built-in
way to automate it.
This transformer reorders statements at the AST level so mocks run before imports.
Prerequisites
Requires @rbxts/jest and
@rbxts/jest-globals.
Install
pnpm i -D rbxts-transformer-jestSetup
Add to your tsconfig.json:
{
"compilerOptions": {
"plugins": [
{
"transform": "rbxts-transformer-jest",
},
],
},
}Before / After
Input:
import { jest } from "@rbxts/jest-globals";
import { MyService } from "./my-service";
const mockHandler = jest.fn();
jest.mock("./my-service", () => ({ handler: mockHandler }));Output (reordered at compile time):
import { jest } from "@rbxts/jest-globals";
const mockHandler = jest.fn();
jest.mock("./my-service", () => ({ handler: mockHandler }));
import { MyService } from "./my-service";The @rbxts/jest-globals import always stays first. Mock-prefix variables
referenced in factories get hoisted alongside the mock call.
String Require Support
The transformer can resolve package specifiers like "@rbxts/services" into
Roblox instance paths at compile time, so you can write:
jest.mock<typeof import("@rbxts/services")>("@rbxts/services", () => {
return { Workspace: {} as Workspace };
});This compiles to the equivalent of:
jest.mock(game:GetService("ReplicatedStorage"):FindFirstChild("rbxts_include"):FindFirstChild("node_modules"):FindFirstChild("@rbxts"):FindFirstChild("services"), function() ... end)Note: You must patch
@rbxts/jesttypes to accept astringas the first argument tojest.mock()andjest.unmock(). The upstream types only acceptModuleScriptand do not account for string specifiers being transformed at compile time.
