Lesson 2 of 6
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.
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
1Forty 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.
Which of these checks need a running Play session (rather than only numbers)?
Answer
Walking onto Pad1 raises leaderstats.Coins by 5; The HUD shows Idle after the round. Walking onto a pad and reading the HUD need the real game in Play. The spend, the damage and the phase order are arithmetic and can be unit tested.
Open this step in lesson mode · Link to this step · This confused me
2Two 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 each bug to the test most likely to catch it first.
Answer
trySpend accepts a negative amount and adds coins: A unit test of trySpend; ShopService listens to a remote called ShopBuys, but the client fires ShopBuy: A playtest that clicks Buy; Cooldown goes back to Active instead of Idle: A unit test of the phase rule; MapBuilder runs after CombatService, so the wrench is missing on first spawn: A playtest that checks the wrench exists. Logic inside one function is a unit-test bug. Names, order and wiring between services only show up when the whole game runs.
Open this step in lesson mode · Link to this step · This confused me
3Make 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.
-- 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.
local function trySpend(balance, amount)
if amount <= 0 or balance < amount then
return false, balance
end
return true, balance - amount
end
local function show(balance, amount)
local ok, after = trySpend(balance, amount)
print(tostring(ok) .. " " .. after)
end
show(80, 25)
show(40, 40)
show(24, 25)
show(50, -10)
true 55
true 0
false 24
false 50Which version of a damage rule is pure?
Answer
function hpAfter(max, dmg, hits) return math.max(0, max - dmg * hits) end. The first takes numbers and returns a number. The others change an object, read the world or wait, so a test would need the game running.
Open this step in lesson mode · Link to this step · This confused me
4Jest-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.
This spec errors before it can pass or fail. Which line is wrong?
describe("healthAfterHits", function()
it("leaves 32 after two hits", function()
expect(Rules.healthAfterHits(100, 34, 2)):toBe(32)
end)
end)
Answer
Line 3: expect(Rules.healthAfterHits(100, 34, 2)):toBe(32). Fixed: expect(Rules.healthAfterHits(100, 34, 2)).toBe(32). Jest-Lua matchers are called with a dot. With a colon, the matcher receives the expectation object as an extra first argument and errors.
Open this step in lesson mode · Link to this step · This confused me
5Install 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.

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
wally.tomltest.project.jsonunit/run.server.luauunit/specs/MatchRules.spec.luau
Check out
m14-ship, inspect[dev-dependencies]inwally.toml, and runwally install.You should see wally install downloads DevPackages/Jest and DevPackages/JestGlobals at version 3.10.0.
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.
Open
beacon-yard-tests.rbxlxin Studio. Stay in Edit mode (do NOT press Play), paste the contents ofunit/run.server.luauinto 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.
Open this step in lesson mode · Link to this step · This confused me
6Mock 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.
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.
Why pass the store into saveProfile instead of calling DataStoreService:GetDataStore inside it?
Answer
A test can pass a fake store that answers instantly and records the calls. When the caller supplies the store, the game passes the real one and the test passes a mock. Nothing else in the function has to change.
Open this step in lesson mode · Link to this step · This confused me
7Where 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.
All your mocked save tests pass. Which bug can they still miss?
Answer
UpdateAsync throws in production and the save code never retries. A mock that always succeeds never exercises the failure path. Make a second mock that throws (mockImplementation with error) and test that the code retries, as DataService.saveUser does four times.
Open this step in lesson mode · Link to this step · This confused me
8Where 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
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| Jest-Lua | The 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. |
| TestEZ | Roblox'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 harness | A 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 scripts | A 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.
Where can a Jest-Lua suite run?
Answer
In Studio, from the command bar in Edit mode on the built test place; On a Roblox server through Open Cloud Luau Execution. Jest-Lua runs where the engine runs: Studio (in Edit mode, not Play, because it needs ModuleScript.Source / debug.loadmodule), or a headless server started by Luau Execution. Lune and Node have no Roblox engine.
Open this step in lesson mode · Link to this step · This confused me
9What 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")
A player reports that 0-coin purchases succeed. Put the professional's steps in order.
Answer
1. Write a test that calls trySpend with an amount of 0 and expects false 2. Run it and watch it fail 3. Change trySpend so the test passes 4. Run the whole suite to check nothing else broke 5. Merge with the test in place. A test that failed first proves it can catch the bug. Keeping it in the suite stops the bug from coming back.
Open this step in lesson mode · Link to this step · This confused me
10Challenges
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'
Hints
- Use the shop prices: Speed is 25 and Shield is 40.
- Edge cases sit at the boundary: exactly enough, one short, zero.
A player has 40 coins and buys the Shield for 40. How many coins should trySpend leave?
Answer
0 coins. 40 is not fewer than 40, so the spend succeeds and leaves 0. Exact balances are the classic off-by-one.
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
Hints
- jest.fn(function() error("throttled") end) makes a mock that throws.
- Count calls with toHaveBeenCalledTimes.
- DataService.saveUser tries four times. Your function can take the number of attempts as an argument so the test does not wait.
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:
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
Hints
- Compare trySpend with DataService.trySpend line by line.
- Two hits of 34 on 100 leave 32. Three leave 0, not -2.
- The round order is Idle, Active, Cooldown, Idle.
Open this step in lesson mode · Link to this step · This confused me
11Recap
Recap
- Pull rules out of services into pure functions; unit test those in unit/specs/*.spec.luau, and keep playtests for wiring.
- 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.
- 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.
Queued for review
Open this step in lesson mode · Link to this step · This confused me