JSPM

rbxts-transformer-jest

0.0.5
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 17
  • Score
    100M100P100Q67732F
  • License MIT

A Jest transformer for Roblox TypeScript (rbxts) projects.

Package Exports

  • rbxts-transformer-jest
  • rbxts-transformer-jest/package.json

Readme

rbxts-transformer-jest

npm version CI License: MIT

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-jest

Setup

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/jest types to accept a string as the first argument to jest.mock() and jest.unmock(). The upstream types only accept ModuleScript and do not account for string specifiers being transformed at compile time.

License

MIT