Unit tests with Jest-Lua

Write unit tests for a Roblox game with Jest-Lua. Test Beacon Yard's pure rules in unit/specs/*.spec.luau, mock slow dependencies, run the test place from Studio's command bar in Edit mode, and understand what CI checks.

Tool lesson, about 70 minutes, 11 steps

By the end you can

  • Pull a game rule such as trySpend out of a service into a pure function a test can call
  • Write describe, it and expect specs for Jest-Lua, including a mock in place of a slow dependency
  • Explain how Beacon Yard runs Jest-Lua in Edit mode from test.project.json and where Jest-Lua can and cannot run
  • Choose between unit tests and the playtest suite for a given bug

Before this: Debugging: breakpoints, the console, a method, The toolchain: Rokit, Wally, pesde, StyLua, Selene, luau-lsp, ModuleScripts and require

Step 1 of 11

Forty seconds to test one rule

Beacon Yard's playtest suite proves the shop works by doing what a player does: it gives your character 80 coins, buys Speed, and checks that 55 are left and WalkSpeed is 24. It is real, and it is slow. Every run waits for Play to start, for the yard to be built and for a whole round to pass.

Now look at the rule it is really checking:

function DataService.trySpend(player: Player, amount: number): boolean
	local profile = waitProfile(player)
	if not profile or amount <= 0 or profile.coins < amount then
		return false
	end
	profile.coins -= amount
	pushCoins(player)
	return true

Five lines. The decision (amount <= 0 or profile.coins < amount) needs no player, no character and no Play session. If you could call it with two numbers, you could check twenty cases in a millisecond.

Choose all that apply

Which of these checks need a running Play session (rather than only numbers)?

Which of these checks need a running Play session (rather than only numbers)?

Press 1 to 5 to choose, Enter to check.

Link to this step · This confused me

Step 2 of 11

Two kinds of test

A Unit testUnit testA test that calls one small piece of code with chosen inputs and checks the output.Think of it as testing one gear on the bench instead of driving the whole car. calls one small piece of code with chosen inputs and checks the output. It runs in milliseconds, has no network and no randomness, and fails with a message that points at one function.

An integration test (Beacon Yard calls them playtests) runs the real game and checks that the pieces work together. It catches wiring bugs a unit test never sees: a remote with the wrong name, a service started in the wrong order.

Professional teams keep both: many fast unit tests at the bottom, fewer slow playtests on top. The next lesson is the playtest suite. This one is the fast layer.

Match the pairs

Match each bug to the test most likely to catch it first.

Link to this step · This confused me

Step 3 of 11

Make the rule pure

DataService.trySpend mixes the rule with the profile table and the leaderboard push. To unit test the rule, pull it out into a Pure functionPure functionA function whose output depends only on its arguments and that changes nothing outside itself.Think of it as a calculator key: the same buttons always give the same answer.: same inputs, same output, no side effects.

luau
-- A pure-function module shape (like MatchRules or DataMigration in m14-ship)
local Rules = {}
 
function Rules.trySpend(balance: number, amount: number): (boolean, number)
	if amount <= 0 or balance < amount then
		return false, balance
	end
	return true, balance - amount
end
 
return Rules

DataService.trySpend then becomes a thin wrapper: read profile.coins, call Rules.trySpend, write the result back, push leaderstats. The service keeps the side effects; the rule becomes testable. Predict all four outputs (including exact balance 40/40 and negative spend -10) before pressing Run.

Luau
Ctrl Enter runs the cell. Checked against the expected output
Choose one

Which version of a damage rule is pure?

Which version of a damage rule is pure?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 4 of 11

Jest-Lua: describe, it, expect

Jest-LuaJest-LuaThe Luau port of the Jest test framework for Roblox.Think of it as jest, the JavaScript test runner, rebuilt for Luau and the Roblox engine. is the Luau port of Jest, the JavaScript test framework. Beacon Yard installs the community Wally packages jsdotlua/jest@3.10.0 and jsdotlua/jest-globals@3.10.0 from jsdotlua/jest-lua1 (Roblox also maintains its own official upstream fork at Roblox/jest-roblox, used for its app, core scripts and Studio plugins2). Both share the same describe, it, expect and jest.fn() API3.

A spec file names what it tests with describe, each case with it, and each check with expect. Here is a real spec from Beacon Yard's m14-ship milestone (unit/specs/MatchRules.spec.luau):

local JestGlobals = require(ReplicatedStorage.DevPackages.JestGlobals)
local MatchRules = require(ServerStorage.Server.MatchRules)
 
local describe = JestGlobals.describe
local it = JestGlobals.it
local expect = JestGlobals.expect
 
describe("MatchRules.plan", function()
	it("sends a full group at once", function()
		local group = MatchRules.plan({ { userId = 1, at = 100 }, { userId = 2, at = 101 } }, 101, 2, 20)
		expect(group).toEqual({ 1, 2 })
	end)
 
	it("takes only as many as the group holds", function()
		local group = MatchRules.plan(
			{ { userId = 1, at = 100 }, { userId = 2, at = 100 }, { userId = 3, at = 100 } },
			100,
			2,
			20
		)
		expect(group).toEqual({ 1, 2 })
	end)
 
	it("keeps a lone player waiting until the wait is up", function()
		expect(MatchRules.plan({ { userId = 1, at = 100 } }, 105, 2, 20)).toBeNil()
		expect(MatchRules.plan({ { userId = 1, at = 100 } }, 120, 2, 20)).toEqual({ 1 })
	end)
 
	it("counts a player queued twice once", function()
		expect(MatchRules.plan({ { userId = 1, at = 100 }, { userId = 1, at = 101 } }, 101, 2, 20)).toBeNil()
	end)
 
	it("sends nobody from an empty queue", function()
		expect(MatchRules.plan({}, 100, 2, 20)).toBeNil()

Note the Luau twist: matchers are called with a dot, expect(x).toBe(1), not a colon3.

Find the broken line

This spec errors before it can pass or fail. Which line is wrong?

This spec errors before it can pass or fail. Which line is wrong?

Press 1 to 5 to choose, Enter to check.

Link to this step · This confused me

Step 5 of 11

Install it with Wally and run in Edit mode

Jest-Lua is a development dependency: tests need it, players never do. At m14-ship, Beacon Yard pins jsdotlua/jest@3.10.0 and jsdotlua/jest-globals@3.10.0 under [dev-dependencies] in wally.toml:

[dev-dependencies]
Jest = "jsdotlua/jest@3.10.0"
JestGlobals = "jsdotlua/jest-globals@3.10.0"

wally install puts them in DevPackages/, and test.project.json (not default.project.json) maps DevPackages/ and unit/specs/ into a lightweight test place, while putting src/server/ into ServerStorage so no game scripts boot:

      "UnitTests": {
        "$path": "unit/specs"
      }
    },
    "ServerStorage": {
      "Server": {
        "$path": "src/server"
      }
    },
    "ServerScriptService": {
      "RunUnitTests": {

One crucial Studio rule: run unit/run.server.luau from Studio's command bar in Edit mode, NOT during Play. Jest-Lua relies on debug.loadmodule or ModuleScript.Source to load spec files, which a running Play session does not permit.

Roblox Studio
Roblox Studio Output window after running Jest-Lua from the command bar in Edit mode, showing unit/specs results and UNIT SUITE DONE.

Select a numbered pin, or a row below, to read what it marks.

Running Beacon Yard's unit/specs/*.spec.luau suite in Edit mode prints the Jest-Lua summary and UNIT SUITE DONE.

Build along

m13-art-pass to m14-ship

  • wally.toml
  • test.project.json
  • unit/run.server.luau
  • unit/specs/MatchRules.spec.luau
  1. Check out m14-ship, inspect [dev-dependencies] in wally.toml, and run wally install.

    You should see wally install downloads DevPackages/Jest and DevPackages/JestGlobals at version 3.10.0.

  2. Build the dedicated test place: rojo build test.project.json -o beacon-yard-tests.rbxlx.

    You should see beacon-yard-tests.rbxlx is created without errors.

  3. Open beacon-yard-tests.rbxlx in Studio. Stay in Edit mode (do NOT press Play), paste the contents of unit/run.server.luau into the Command Bar, and press Enter.

    You should see Output lists the unit/specs/*.spec.luau suites (MatchRules, CrawlerBrain, ShopLabels, PlaceRole, DataMigration, FlagService, ReceiptRules) and ends with UNIT SUITE DONE.

Link to this step · This confused me

Step 6 of 11

Mock the slow thing

Some rules depend on something slow or unreliable. Saving a profile calls UpdateAsync on a DataStore, which can take a second, can throw, and in an unpublished place throws every time. A unit test should not wait on that.

The DataStore is a bank vault in another city. A unit test does not drive to the city. It builds a cardboard vault on the desk, a MockMockA stand-in for a real dependency that a test controls and inspects.Think of it as a cardboard bank vault on your desk that answers instantly and writes down every request., that answers instantly and writes down every request it gets.

Think of it as A bank vault in another city

Stored dataRemember: A DataStore is a bank vault in another city.

Jest-Lua makes mock functions with jest.fn(). It returns two values: the mock object, which records calls, and a plain forwarding function for code that insists on a real function3.

luau
local jest = JestGlobals.jest
 
it("saves once with UpdateAsync", function()
	local updateMock, updateFn = jest.fn()
	local fakeStore = { UpdateAsync = updateFn }
 
	saveProfile(fakeStore, 123, { coins = 55, speedOwned = true })
 
	expect(updateMock).toHaveBeenCalledTimes(1)
end)

For this to work, saveProfile must take the store as an argument instead of calling DataStoreService itself. That is the real lesson of mocking: code that receives its dependencies is code you can test.

Choose one

Why pass the store into saveProfile instead of calling DataStoreService:GetDataStore inside it?

Why pass the store into saveProfile instead of calling DataStoreService:GetDataStore inside it?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 7 of 11

Where the cardboard vault breaks

Where does it break?“A bank vault in another city” is a good picture of a datastore. Where does it stop being true?

It breaks here. The vault keeps only the last write for a key, so two servers writing the same key can silently undo each other.

The true model. A DataStore is a remote key-value store with request budgets. Calls are slow and can throw, so code wraps them, retries carefully and uses UpdateAsync or a session lock when more than one server might write.

The real vault keeps only the last write, can be slow, can throw, and can be written by another server at the same moment. Your cardboard vault does none of that unless you make it. A test suite that only mocks success can pass while the game loses coins in production.

Choose one

All your mocked save tests pass. Which bug can they still miss?

All your mocked save tests pass. Which bug can they still miss?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 8 of 11

Where Jest-Lua can run

Jest-Lua runs inside a Roblox engine, because it uses Roblox APIs3. That rules some places in and some out.

Other ways pros do this

OptionWhat it isWhen pros pick itTrade-offs
Jest-LuaThe Luau port of Jest (jsdotlua/jest-lua on Wally; Roblox/jest-roblox upstream): describe, it, expect, mocks, snapshots, fake timers.New projects and studios. It is what Beacon Yard uses at m14-ship and what Roblox uses internally.Needs a Roblox engine to run: Studio (command bar in Edit mode) or Open Cloud Luau Execution.
TestEZRoblox's older BDD test library.Only in legacy codebases that already use it.Archived and read-only on GitHub since 2024. Migrate to Jest-Lua.
A hand-rolled harnessA module that calls functions and prints TEST PASS or TEST FAIL, as Beacon Yard's challenges do.Small projects and learning, or when you cannot add packages.No mocks, no reports, no watch mode. You maintain it.
Lune scriptsA standalone Luau runtime outside Roblox.Tests for pure Luau tools and build scripts that never touch the engine.Has no game engine, so Jest-Lua does not run on it. The jest-lua README still lists Lune support as help wanted.

What about CI? At m14-ship, Beacon Yard's .github/workflows/ci.yml lints and type-checks unit/ and builds build/beacon-yard-tests.rbxlx from test.project.json, while .github/workflows/deploy.yml uses scripts/publish-place.mjs to publish places. Beacon Yard's CI does not run cloud tests. Running Jest-Lua automatically on every pull request requires either run-in-roblox (which opens Studio on a Windows or macOS runner, last updated in 20244) or Open Cloud Luau Execution (which runs a script headlessly on a Roblox server against a published place version, up to 5 minutes per task and 10 incomplete tasks per place5). Roblox published a sample pipeline for that flow (place-ci-cd-demo), now archived and labelled a sample6. Module 13's Testing at scale: cloud CI, bots and soak tests expands this into contract tests, soak harnesses and headless load benchmarks.

Choose all that apply

Where can a Jest-Lua suite run?

Where can a Jest-Lua suite run?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 9 of 11

What a professional tests

The Beacon Yard challenge files are already shaped like unit tests: plain functions in a learner file, and a test module that calls them with numbers. The functions do not need a player. You still press Play to start the server's Course Runner and get a pass code.

	run = function(ctx: ChallengeCtx?)
		expect(ctx, "shield_equal", Work.shieldHeld(85, 85), "unchanged health should hold")
		expect(ctx, "shield_heal_1", Work.shieldHeld(85, 86), "a 1 point heal should hold")
		expect(ctx, "shield_heal_2", Work.shieldHeld(85, 87), "a 2 point heal should hold")
Put in order

A player reports that 0-coin purchases succeed. Put the professional's steps in order.

  1. Run the whole suite to check nothing else broke
  2. Change trySpend so the test passes
  3. Merge with the test in place
  4. Write a test that calls trySpend with an amount of 0 and expects false
  5. Run it and watch it fail

Link to this step · This confused me

Step 10 of 11

Challenges

Level 1, Apprentice

Challenge

Write, on paper or in a comment, the it names and expect lines for a trySpend suite.

Start from
The game at milestone m06 (download)

Done means

  • You list five trySpend cases with their expected results, including 0 and a negative amount
  • Each case names the exact numbers, not just 'works'

Meet the criteria above, then record your own result. No test grades this check.

Work it out

A player has 40 coins and buys the Shield for 40. How many coins should trySpend leave?

coins

Level 2, Builder

Challenge

Write a save function and two mocked tests for it, one for success and one for failure.

Start from
The game at milestone m06 (download)

Done means

  • A saveProfile function takes the store as an argument
  • One test passes a mock that succeeds and checks it was called once
  • One test passes a mock that throws and checks the function returns false after retrying

Meet the criteria above, then record your own result. No test grades this check.

Level 3, Professional

Challenge

Fix the three rules in challenges/unit_tests_work.luau on m14-ship. Press Play and run this in the server command bar:

luau
game.ServerScriptService.RunGameTests:Invoke("unit-tests")
Start from
The game at milestone m14 (download)
Grade it
In Studio, press Play, then run game.ServerScriptService.RunGameTests:Invoke("unit-tests") in the server command bar. Copy the pass code from Output.

Done means

  • trySpend buys with an exact balance and refuses zero and negative amounts
  • healthAfterHits uses the hit count and never goes below 0
  • nextPhase sends Cooldown to Idle and ignores events that do not apply
  • challenges/unit-tests.luau prints TEST PASS for all thirteen cases

The Course Runner prints this code when the test passes.

Link to this step · This confused me

Step 11 of 11

Recap

Recap

  1. Pull rules out of services into pure functions; unit test those in unit/specs/*.spec.luau, and keep playtests for wiring.
  2. Jest-Lua (jsdotlua/jest@3.10.0 in Beacon Yard's m14-ship) gives describe, it, expect with a dot, and jest.fn() mocks. TestEZ is archived.
  3. Run Jest-Lua in Studio from the command bar in Edit mode (not Play) on test.project.json, or via Open Cloud Luau Execution. Beacon Yard's CI builds and type-checks the test place without running cloud tests.

A DataStore is a bank vault in another city, until the vault keeps only the last write for a key, so two servers writing the same key can silently undo each other.

Next Integration playtests

Link to this step · This confused me