TypeScript

Toy Robot Simulator with Test-Driven Development (TDD) in TypeScript

The Toy Robot Simulator is a classic coding challenge. A robot sits on a 5x5 grid. It can be placed, moved forward, rotated left or right, and report its ...

17 Apr 2024

Toy Robot Simulator with Test-Driven Development (TDD) in TypeScript

The Toy Robot Simulator is a classic coding challenge. A robot sits on a 5x5 grid. It can be placed, moved forward, rotated left or right, and report its position. Simple rules, but enough complexity to make TDD worthwhile.

I built this in TypeScript using test-driven development. Tests first, implementation second.

You can follow along in an empty project. Node.js, npm, TypeScript and a test runner are all you need:

Bash
npm init -y
npm install --save-dev typescript jest ts-jest @types/jest

The approach: tests first

TDD means writing a failing test before writing any code. You describe what the robot should do, watch it fail, then make it pass.

Start with the simplest behavior and build up. Place the robot. Check its position. Move it. Rotate it. Each step gets its own test.

Why TDD works here

The robot has clear inputs and outputs. Place it at (0,0) facing North, move once, it should be at (0,1). That's easy to test.

The benefit: every edge case gets covered. What happens when the robot tries to walk off the table? The test tells you.

The cost: it takes longer upfront. You write more code before you see anything "work." But when you're done, you're done. No manual testing, no surprise bugs at the edges.

Typescript
import Board from "../Board";

Build the rest yourself and the exercise pays off properly. Add obstacles. Make the grid bigger. Break things and let the tests catch you.

Go further
Live cohort on Maven

AI Transformation for Organisational Leaders

For directors, heads of function and founders: eight live evening sessions with Ehsan Gazar and Anoosh Zeighami, ending with a one-page 2027 AI plan for your organisation, built on a real workflow and ready for your leadership team.

$1,495, or $1,045 with code EARLYBIRD until 23 Oct.

View the live cohort

Keep reading