Skip to content

Instantly share code, notes, and snippets.

@Oluwasetemi
Last active September 21, 2021 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oluwasetemi/cd89263c6bc8d4960b05ffa683c03431 to your computer and use it in GitHub Desktop.
Save Oluwasetemi/cd89263c6bc8d4960b05ffa683c03431 to your computer and use it in GitHub Desktop.
Testing John Conway's [Game of Life](https://playgameoflife.com/)
Testing John Conway's [Game of Life](https://playgameoflife.com/)
The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. It is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves.
It is Turing complete and can simulate a universal constructor or any other Turing machine.

Testing John Conway's Game of Life

Available Scripts

In the project directory, you can run:

npm install
# or
yarn

install the dependencies needed for the test application to run

npm run test
# or
yarn test

Launches the test runner in the console.

Nouns

  • Depending on the initial conditions
  • The Game.
  • Cell: Boolean
  • A few mathematical rules

class Game

  • initial conditions
  • public Arrays[x,y]: Boolean
  • implements a set of mathematicial rules
  • it has an initiation function(x: Int, y: Int, Array[x: Int,y: Int], steps)

Rules

For a space that is populated

  • Each cell with one or no neighbors dies, as if by solitude.

  • Each cell with four or more neighbors dies, as if by overpopulation.

  • Each cell with two or three neighbors survives.

For a space that is empty or unpopulated

  • Each cell with three neighbors becomes populated.

Triple A tests

// Arrange, Act, Assert

  • Arrange: Prepare the System under test to a state you want
  • Act: Operation you want to verify. Operation should change the system state
  • Assert: Verify the new state is correct

Create 5 tests

  • That tests the game initialization
  • 2-5 Tests each of the rules of the game
module.exports = {
presets: [
'@babel/preset-env',
'@babel/preset-typescript',
// '@babel/preset-react',
],
};
/**
* Arrange,Act, Assert
* create 5 tests
* 1.That tests the game initialization
* 2-5 test each rules of the game
*
* class Game
- initial conditions
- cell - public Arrays[x,y]: Boolean
- implements a set of mathematical rules
- it has an initiation function(x: Int, y: Int, Array[x: Int,y: Int], steps)
*/
class Game {
board: boolean[][];
step: number;
constructor(
row: number,
column: number,
initialData?: Array<boolean[]>,
steps: number = 1,
) {
this.board = this.createBoard(row, column, initialData);
this.step = steps;
}
private createBoard(
row: number,
column: number,
initialData?: Array<boolean[]>,
) {
let initialDataRow = initialData?.length;
let initialDataColumn = (index: number, initialData: boolean[][]) =>
initialData[index].length;
// if seed data does not have the same number of rows and column throw an error
if (initialData) {
if (row === initialDataRow) {
for (let index = 0; index < initialData?.length; index += 1) {
if (column !== initialDataColumn(index, initialData)) {
throw new Error(`Invalid seed Column ${index}`);
}
}
} else {
throw new Error('Invalid seed row');
}
return initialData;
} else {
const board: Array<boolean[]> = [];
for (let index = 0; index < row; index++) {
board[index] = new Array(column);
board[index].fill(false);
}
return board;
}
}
private neighbourCount(
rowIndex: number,
columnIndex: number,
boardState: boolean[][],
) {
const possibleNeighbours = [];
const confirmPosition =
(board: boolean[][]) => (pointX: number, pointY: number) => {
// console.log({ x, y });
if (pointX === -1 || pointY === -1) return null;
return board[pointX] && board[pointX][pointY] ? [pointX, pointY] : null;
};
const checkPositionOnBoard = confirmPosition(boardState);
// this is used to create a square of coordinates round rowIndex, columnIndex
const rowNegative = rowIndex - 1;
const rowPositive = rowIndex + 1;
const columnNegative = columnIndex - 1;
const columnPositive = columnIndex + 1;
// diagonals
possibleNeighbours.push(checkPositionOnBoard(rowNegative, columnNegative));
possibleNeighbours.push(checkPositionOnBoard(rowNegative, columnPositive));
possibleNeighbours.push(checkPositionOnBoard(rowPositive, columnNegative));
possibleNeighbours.push(checkPositionOnBoard(rowPositive, columnPositive));
// opposites
possibleNeighbours.push(checkPositionOnBoard(rowNegative, columnIndex));
possibleNeighbours.push(checkPositionOnBoard(rowPositive, columnIndex));
possibleNeighbours.push(checkPositionOnBoard(rowIndex, columnNegative));
possibleNeighbours.push(checkPositionOnBoard(rowIndex, columnPositive));
const neighbours = possibleNeighbours.filter(Boolean).length;
// clean up the coords to return length of neighbours (count)
return neighbours;
}
private putEmptyArrayInResult(count: number, result: boolean[][] = []) {
for (let index = 0; index < count; index += 1) {
result.push([]);
}
return result;
}
runStep() {
let result: boolean[][] = this.putEmptyArrayInResult(this.board.length);
// for (let i = 0; i < this.board.length; i += 1) {
// result.push([]);
// }
for (let indexX = 0; indexX < this.board.length; indexX += 1) {
for (let indexY = 0; indexY < this.board[indexX].length; indexY += 1) {
const cell = this.board[indexX][indexY];
const neighbourCount = this.neighbourCount(indexX, indexY, this.board);
// if cell is alive
// * For a space that is populated:
if (cell) {
//* Each cell with one or no neighbors dies, as if by solitude.
if (neighbourCount <= 1) {
result[indexX][indexY] = !cell;
}
//* Each cell with two or three neighbors survives.
if (neighbourCount === 2 || neighbourCount === 3) {
result[indexX][indexY] = cell;
}
//* Each cell with four or more neighbors dies, as if by overpopulation.
if (neighbourCount >= 4) {
result[indexX][indexY] = !cell;
}
} else {
// if cell is dead
// * For a space that is empty or unpopulated
// Each cell with three neighbors becomes populated.
if (neighbourCount === 3) {
result[indexX][indexY] = !cell;
} else {
result[indexX][indexY] = cell;
}
}
}
}
// tried to use recursion here to runStep if this.step more than 1
return result;
}
simulateGame() {
let result;
for (let index = 0; index < this.step; index += 1) {
// console.log(`running ${i}`);
result = this.runStep();
this.board = result;
}
// console.log('done');
return result;
}
}
let a = new Game(
3,
3,
[
[true, false, false],
[false, true, false],
[true, false, true],
],
3,
);
let res = a.simulateGame();
console.log(res);
describe('The Game of Life Implementation', () => {
describe('Game class', () => {
test('should setup a game board with 4 rows and 5 columns with initial data with steps', () => {
const rows = 4;
const columns = 5;
const steps = 2;
const initialData = [
[true, false, false, true, false],
[true, false, false, true, true],
[false, true, false, false, true],
[false, false, true, true, false],
];
const gameBoard = new Game(rows, columns, initialData, steps);
expect(gameBoard).toBeInstanceOf(Game);
expect(gameBoard).toHaveProperty('board');
expect(gameBoard.board).toHaveLength(rows);
expect(gameBoard.board[0]).toHaveLength(columns);
expect(gameBoard.board).toStrictEqual(initialData);
expect(gameBoard.step).toEqual(steps);
});
});
describe('Game rules', () => {
test('For a space that is populated:Each cell with one or no neighbors should die', () => {
const rows = 3;
const columns = 3;
const steps = 1;
const initialData = [
[true, false, false],
[false, true, false],
[true, false, true],
];
const gameBoard = new Game(rows, columns, initialData, steps);
let result = gameBoard.runStep();
expect(result[0][0]).toBe(!gameBoard.board[0][0]);
expect(result[2][0]).toBe(!gameBoard.board[2][0]);
expect(result[2][2]).toBe(!gameBoard.board[2][2]);
});
test('For a space that is populated:Each cell with four or more neighbors should die', () => {
const rows = 5;
const columns = 3;
const steps = 1;
const initialData = [
[true, false, false],
[false, false, false],
[true, true, true],
[true, true, false],
[false, false, false],
];
const gameBoard = new Game(rows, columns, initialData, steps);
let result = gameBoard.runStep();
expect(result[2][1]).toBe(!gameBoard.board[2][1]);
expect(result[3][1]).toBe(!gameBoard.board[3][1]);
});
test('For a space that is populated:Each cell with two or three neighbors should survive.', () => {
const rows = 5;
const columns = 3;
const steps = 1;
const initialData = [
[true, false, false],
[false, false, false],
[true, true, true],
[true, true, false],
[false, false, false],
];
const gameBoard = new Game(rows, columns, initialData, steps);
let result = gameBoard.runStep();
expect(result[2][0]).toBe(gameBoard.board[2][0]);
expect(result[2][2]).toBe(gameBoard.board[2][2]);
expect(result[3][0]).toBe(gameBoard.board[3][0]);
});
test('For a space that is empty or unpopulated:Each cell with three neighbors should populated.', () => {
const rows = 5;
const columns = 3;
const steps = 1;
const initialData = [
[true, false, false],
[false, false, false],
[true, true, true],
[true, true, false],
[false, false, false],
];
const gameBoard = new Game(rows, columns, initialData, steps);
let result = gameBoard.runStep();
expect(result[1][0]).toBe(!gameBoard.board[1][0]);
expect(result[3][2]).toBe(!gameBoard.board[3][2]);
});
});
});
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/configuration
*/
export default {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/c1/8xbdz7kd66742k6wzt95j0500000gn/T/jest_dx",
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: 'coverage',
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: 'v8',
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "jsx",
// "ts",
// "tsx",
// "json",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};
{
"name": "unit-test-practice",
"version": "1.0.0",
"main": "index.js",
"author": "Oluwasetemi Ojo <setemiojo@gmail.com> (https://oluwasetemi.dev/)",
"license": "MIT",
"devDependencies": {
"@babel/preset-env": "^7.15.6",
"@babel/preset-typescript": "^7.15.0",
"@types/jest": "^27.0.1",
"jest": "^27.2.0",
"ts-node": "^10.2.1",
"typescript": "^4.4.3"
},
"scripts": {
"test": "jest"
}
}
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment