20 - Setup Tests

The @replay/test package provides a platform to automate gameplay tests for our game. We can write our tests as though we're playing the game for real, without needing to know much about the internal workings of our code.

Using Jest we can write an initial test to confirm we can start the game.

In __tests__/game.test replace what's there with the code on the right. We pass our Game Sprite (and gameProps) into the testSprite function, which returns some more useful functions for inspecting our game. Since the test platform doesn't know if we want to run on web or iOS, we need to supply the inputs we'd expect on those platforms through initInputs.

Then we have to wait for our loading screen to pass by calling await resolvePromises().

Below that getByText(mainMenuText) searches all t.text Textures that match the string passed in. This confirms that our main menu is visible on the initial render.

Next we call updateInputs to simulate a mouse click or tap to start, then progress one frame with nextFrame. After that we reset the inputs and progress one more frame. Now that the game's started, we confirm in our test the main menu isn't visible any more.

BackNext
1import { testSprite } from "@replay/test";
2import { Game, gameProps } from "..";
3
4test("Can start game", async () => {
5 const initInputs = {
6 pointer: {
7 pressed: false,
8 numberPressed: 0,
9 justPressed: false,
10 justReleased: false,
11 x: 0,
12 y: 0,
13 },
14 keysDown: {},
15 keysJustPressed: {},
16 };
17 const mainMenuText = "Start";
18
19 const { nextFrame, updateInputs, getByText, resolvePromises } = testSprite(
20 Game(gameProps),
21 gameProps,
22 {
23 initInputs,
24 }
25 );
26
27 await resolvePromises();
28 nextFrame();
29
30 expect(getByText(mainMenuText).length).toBe(1);
31
32 updateInputs({
33 pointer: {
34 pressed: false,
35 numberPressed: 1,
36 justPressed: false,
37 justReleased: true,
38 x: 0,
39 y: 0,
40 },
41 keysDown: {},
42 keysJustPressed: {},
43 });
44 nextFrame();
45
46 updateInputs(initInputs);
47 nextFrame();
48
49 // Main menu gone, game has started
50 expect(getByText(mainMenuText).length).toBe(0);
51});
52