@@ -67,7 +67,7 @@ it('should declare player 1 as the winner', () => {
6767 client .moves .clickCell (5 );
6868
6969 // get the latest game state
70- const { G , ctx } = client .store . getState ();
70+ const { G , ctx } = client .getState ();
7171
7272 // the board should look like this now
7373 expect (G .cells ).toEqual ([' 0' , ' 0' , null , ' 1' , ' 1' , ' 1' , null , null , ' 0' ]);
@@ -76,9 +76,72 @@ it('should declare player 1 as the winner', () => {
7676});
7777```
7878
79- ! > Note that we imported the vanilla JavaScript client, not the
79+ ? > Note that we imported the vanilla JavaScript client, not the
8080one from ` boardgame.io/react ` .
8181
82+ ### Testing Randomness
83+
84+ If you are testing a move that uses the [ Random API] ( /random ) , by definition
85+ you can’t always expect the same result, making it harder to test. In this
86+ case, you can use one of the following strategies.
87+
88+ #### Fixed PRNG seed
89+
90+ You can set ` seed ` in your game object. This will be used to initialise the
91+ Random API’s internal state and you’ll see a predictable sequence of results
92+ from calls to random API methods:
93+
94+ ``` js
95+ import { Client } from ' boardgame.io/client' ;
96+
97+ const Game = {
98+ moves: {
99+ rollDice : (G , ctx ) => {
100+ G .roll = ctx .random .D6 ();
101+ },
102+ },
103+ };
104+
105+ it (' updates G.roll with a random number' , () => {
106+ const client = Client ({
107+ // Set seed so PRNG always starts in same state
108+ game: { ... Game, seed: ' fixed-seed' },
109+ });
110+ client .moves .rollDice ();
111+ const { G } = client .getState ();
112+ expect (G .roll ).toMatchInlineSnapshot (` 4` );
113+ });
114+ ```
115+
116+ #### Override Random API <small >` since v0.49.9 ` </small >
117+
118+ If you need to test specific random outcomes, you can override the Random
119+ API entirely to allow complete control of the results of API methods.
120+
121+ ``` js
122+ import { Client } from ' boardgame.io/client' ;
123+ import { MockRandom } from ' boardgame.io/testing' ;
124+
125+ // Create a mock of the random plugin, where the D6 method always returns 6.
126+ // Any methods you don’t provide an implementation for will behave as usual.
127+ const randomPlugin = MockRandom ({
128+ D6 : () => 6 ,
129+ });
130+
131+ it (' rolls a six' , () => {
132+ const client = Client ({
133+ game: {
134+ ... Game,
135+ // Add the random plugin mock to the game’s plugins.
136+ plugins: [... (Game .plugins || []), randomPlugin]
137+ },
138+ });
139+ client .moves .rollDice ();
140+ const { G } = client .getState ();
141+ expect (G .roll ).toMatchInlineSnapshot (` 6` );
142+ });
143+ ```
144+
82145### Multiplayer Tests
83146
84147Use the local multiplayer mode to simulate multiplayer interactions
0 commit comments