Front-end unit testing
Unit tests run your game's JavaScript or TypeScript locally, without opening a Studio table. They are useful for checking which elements appear, how notifications change the interface, and which action a click sends to the server.
This guide uses Vitest to run tests, make assertions, and replace dependencies. jsdom provides document, window, and other browser APIs. The same setup supports JavaScript and TypeScript and works alongside the Studio project's Rollup build.
Install the test tools
Install the tools from your game's root directory:
If npm reports an unsupported Node.js version, update to the latest Node.js LTS release and run the command again.Add these commands to the existing scripts object in package.json. Keep your existing build and watch commands:
The PHP unit testing guide provides an optional test:php command, so you can run each test suite by name.
Commit package.json and package-lock.json with your tests. Another developer can run npm ci to install the same versions. Keep node_modules, .vitest, and coverage out of Git and SFTP uploads. Add them to your existing .gitignore and .vscode/sftp.json ignore lists if needed. The tests do not need to be uploaded to Studio.
Configure the test runner
Create this file in your game's root directory. The .mjs extension makes it an ES module without changing the rest of your project's module configuration:
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
environment: 'jsdom',
include: ['src/tests/**/*.test.{js,ts}'],
setupFiles: ['./src/tests/setup.js'],
restoreMocks: true,
unstubGlobals: true,
},
});
Create the setup file below. It clears the DOM and restores real timers after each test. The Reversi JavaScript module also loads bga-animations when imported; the substitute allows that import without downloading a library from BGA. These tests do not construct an animation manager, so they need no animation implementation. Other unexpected library imports fail immediately.
import { afterEach, vi } from 'vitest';
vi.stubGlobal('importEsmLib', async (name) => {
if (name === 'bga-animations') {
return {};
}
throw new Error(`Unexpected BGA library import: ${name}`);
});
afterEach(() => {
document.body.replaceChildren();
vi.useRealTimers();
});
Keep this setup file as JavaScript for either language. Vitest loads it before importing each test file. restoreMocks restores spied-on methods, and unstubGlobals restores globals replaced with vi.stubGlobal() before the next test. If a test needs a global while it runs, install that substitute in its beforeEach, rather than relying on this import-time substitute.
Example: test Reversi's selectable squares
Use PlayDisc.updatePossibleMoves() from the current Reversi tutorial.
Import the state class
In the JavaScript version, PlayDisc is declared inside modules/js/Game.js. Add this named export at the end of that file so tests can import it:
Create src/tests/PlayDisc.test.js with these imports:
import { beforeEach, describe, expect, it } from 'vitest';
import { PlayDisc } from '../../modules/js/Game.js';
Edit the JavaScript source directly only if you are following the JavaScript version of the tutorial. For a TypeScript project, use the source file described in the next tab.
The TypeScript state class is already exported. Create src/tests/PlayDisc.test.ts with these imports:
import { beforeEach, describe, expect, it } from 'vitest';
import { PlayDisc } from '../ts/States/PlayDisc';
This path follows the skeleton's src/ts/States/ directory. If you placed PlayDisc.ts directly in src/ts/, use ../ts/PlayDisc instead. Import the TypeScript source, so tests do not depend on a previous Rollup build.
Add the tests
Append this code after the imports in the test file you created. It works in both JavaScript and TypeScript:
describe('PlayDisc.updatePossibleMoves', () => {
let state;
beforeEach(() => {
document.body.innerHTML = '<div id="board"></div>';
const board = document.getElementById('board');
for (let y = 1; y <= 8; y++) {
for (let x = 1; x <= 8; x++) {
board.insertAdjacentHTML('beforeend',
`<div id="square_${x}_${y}" class="square"></div>`);
}
}
// This method only uses the DOM, so skip the game and BGA constructor dependencies.
state = Object.create(PlayDisc.prototype);
});
/** Checks that exactly the supplied squares become selectable. */
it('highlights the supplied possible moves', () => {
state.updatePossibleMoves([{ x: 3, y: 5 }, { x: 4, y: 6 }]);
expect(selectableIds()).toEqual(['square_3_5', 'square_4_6']);
});
/** Checks that a new list removes old highlights before adding new ones. */
it('replaces the previous possible moves', () => {
state.updatePossibleMoves([{ x: 3, y: 5 }]);
state.updatePossibleMoves([{ x: 6, y: 4 }]);
expect(selectableIds()).toEqual(['square_6_4']);
});
/** Checks that an empty list clears all highlights, as when leaving the state. */
it('clears the highlights when there are no possible moves', () => {
state.updatePossibleMoves([{ x: 3, y: 5 }, { x: 4, y: 6 }]);
state.updatePossibleMoves([]);
expect(selectableIds()).toEqual([]);
});
});
/** Returns the highlighted square IDs in a stable order for assertions. */
function selectableIds() {
return Array.from(document.querySelectorAll('.square.selectable'),
square => square.id).sort();
}
Object.create(PlayDisc.prototype) gives us the actual state methods without running the constructor. This is sufficient because updatePossibleMoves() only reads and changes DOM elements. For methods that use instance fields, initialize those fields or construct the state with the specific dependencies it needs.
Run all tests, one file, or one test by name:
npm run test:frontend
npm run test:frontend -- src/tests/PlayDisc.test.js
npm run test:frontend -- -t "replaces the previous possible moves"
For TypeScript, use .test.ts in the file command. All three tests should pass. Change an expected square ID to see a failure, then restore it. Use npm run test:frontend:watch to rerun tests when files change.
TypeScript checking
Vitest executes TypeScript but does not type-check it by default. Keep a separate check so a passing test suite does not hide type errors.
For a TypeScript project, create a test configuration that includes your source, tests, and downloaded framework declarations:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": true,
"rootDir": ".",
"skipLibCheck": true
},
"include": ["*.d.ts", "src/ts/**/*.ts", "src/tests/**/*.ts"],
"exclude": ["node_modules"]
}
Add a script to package.json:
Run npm run test:types alongside npm run test:frontend. TypeScript is already a dependency of the skeleton's TypeScript build. Keep tests out of your production build configuration: the skeleton includes src/ts/, while these tests live in src/tests/. If your project includes all of src/, exclude src/tests/ from its production tsconfig.json.
Other framework dependencies
Keep substitutes small and specific to the behavior under test. For example, when testing an action handler, replace bga.actions.performAction with vi.fn().mockResolvedValue({}) and assert the action name and arguments.
Use vi.stubGlobal() for globals such as _, and vi.spyOn() for existing methods. Create fresh dependency objects in beforeEach so calls and mutable data do not carry over between tests. For timers, use vi.useFakeTimers() and advance time explicitly; await asynchronous handlers before checking their results.
If an imported module loads a BGA library and you need more control than the setup above provides, use Vitest's module mocking to replace that module. Keep ES module imports in your tests; no CommonJS conversion or changes to Node's module resolver are needed.
What to test next
Good candidates include a notification updating a counter, a click sending the expected action, a state adding the correct buttons, and leaving a state removing its highlights. When fixing a front-end bug, reproduce it with a test that expects the corrected behavior.
If you came here from a tutorial, return to its unit testing section: