DEV Community

Nicolas DUBIEN
Nicolas DUBIEN

Posted on • Edited on

Advent of PBT 2021 - Day 3

Advent of PBT 2021 — Learn how to use property based testing and fast-check through examples

Today we will cover an algorithm often taken as an example when we talk about tests. While it is most of the time not really representative for real world examples let's cover it...

Our algorithm today is: fizzbuzz.
It comes with the following documentation and prototype:

/**
 * FizzBuzz
 *
 * @param n - The value to consider
 *
 * @returns Fizz if divisible by 3, Buzz if divisible by 5,
 * the number as a string if none of the conditions apply
 */
declare function fizzbuzz(n: number): string;
Enter fullscreen mode Exit fullscreen mode

A more detailed explanation of what you should expect out of it is given by Wikipedia in https://en.wikipedia.org/wiki/Fizz_buzz.

In order to clarify our expectations, we already wrote some examples based tests for it:

it("should be itself for 1, 32 or 121", () => {
  expect(fizzbuzz(1)).toEqual("1");
  expect(fizzbuzz(32)).toEqual("32");
  expect(fizzbuzz(121)).toEqual("121");
});

it("should be Fizz for 3, 6 or 33", () => {
  expect(fizzbuzz(3)).toEqual("Fizz");
  expect(fizzbuzz(6)).toEqual("Fizz");
  expect(fizzbuzz(33)).toEqual("Fizz");
});

it("should be Buzz for 5, 10 or 50", () => {
  expect(fizzbuzz(5)).toEqual("Buzz");
  expect(fizzbuzz(10)).toEqual("Buzz");
  expect(fizzbuzz(50)).toEqual("Buzz");
});

it("should be Fizz Buzz for 15, 30 or 150", () => {
  expect(fizzbuzz(15)).toEqual("Fizz Buzz");
  expect(fizzbuzz(30)).toEqual("Fizz Buzz");
  expect(fizzbuzz(150)).toEqual("Fizz Buzz");
});
Enter fullscreen mode Exit fullscreen mode

How would you cover it with Property Based Tests?

In order to ease your task we provide you with an already setup CodeSandbox, with examples based tests already written and a possible implementation of the algorithm: https://codesandbox.io/s/advent-of-pbt-day-3-vt4j2?file=/src/index.spec.ts&previewwindow=tests

You wanna see the solution? Here is the set of properties I came with to cover today's algorithm: https://dev.to/dubzzz/advent-of-pbt-2021-day-3-solution-366l


Back to "Advent of PBT 2021" to see topics covered during the other days and their solutions.

More about this serie on @ndubien or with the hashtag #AdventOfPBT.

Top comments (0)