Testing Conway's Game of Life
We are going to test our function to make sure that it gives us theoutput that we expect.
Next, we'll want to create some setter and getterfunctions inside our existing impl Universe
block in thewasm_game_of_life/src/lib.rs
file. We are going to create a set_width
and a set_height
function so we can create Universe
s of different sizes.
We are going to create another impl Universe
block inside ourwasm_game_of_life/src/lib.rs
file without the #[wasm_bindgen]
attribute.There are a few functions we need for testing that we don't want to expose toour JavaScript. Rust-generated WebAssembly functions cannot returnborrowed references. Try compiling the Rust-generated WebAssembly with theattribute and take a look at the errors you get.
Now we're going to create our test in the wasm_game_of_life/tests/web.rs
file.
Before we do that, there is already one working test in the file. You canconfirm that the Rust-generated WebAssembly test is working by runningwasm-pack test —chrome —headless
in the wasm-game-of-life
directory.You can also use the —firefox
, —safari
, and —node
options totest your code in those browsers.
In the wasm_game_of_life/tests/web.rs
file, we need to export ourwasm_game_of_life
crate and the Universe
type.
We'll want one for our input spaceship that we'll call the tick
function onand we'll want the expected spaceship we will get after one tick. We picked thecells that we want to initialize as Alive
to create our spaceship in theinput_spaceship
function. The position of the spaceship in theexpected_spaceship
function after the tick of the wascalculated manually. You can confirm for yourself that the cells of the inputspaceship after one tick is the same as the expected spaceship.
Now we will write the implementation for our test_tick
function. First, wecreate an instance of our input_spaceship()
and our expected_spaceship()
.Then, we call tick
on the input_universe
. Finally, we use the assert_eq!
macro to call get_cells()
to ensure that input_universe
andexpected_universe
have the same Cell
array values. We add the#[wasm_bindgen_test]
attribute to our code block so we can test ourRust-generated WebAssembly code and use wasm-pack test
to test theWebAssembly code.
Run the tests within the wasm-game-of-life
directory by runningwasm-pack test —firefox —headless
.