DEV Community

Nicolas DUBIEN
Nicolas DUBIEN

Posted on • Updated on

Advent of PBT 2021 - Day 6

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

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

type Fraction = { numerator: number; denominator: number };

/**
 * Simplify a fraction by reducing (if possible) the numerator
 * and denominator
 *
 * @param f - Fraction to be simplified
 *
 * @returns
 * An equivalent fraction with possibly smaller values for numerator
 * and denominator. Additionally only the numerator should be
 * negative after simplification.
 */
declare function simplifyFraction(f: Fraction): Fraction;
Enter fullscreen mode Exit fullscreen mode

We already wrote some examples based tests for it:

it("should simplify the fraction when numerator is divisible by denominator", () => {
  const out = simplifyFraction({ numerator: 10, denominator: 5 });
  expect(out).toEqual({ numerator: 2, denominator: 1 });
});

it("should simplify the fraction when numerator and denominator have a shared dividor", () => {
  const out = simplifyFraction({ numerator: 4, denominator: 10 });
  expect(out).toEqual({ numerator: 2, denominator: 5 });
});

it("should not simplify when fraction cannot be simplified", () => {
  const out = simplifyFraction({ numerator: 4, denominator: 9 });
  expect(out).toEqual({ numerator: 4, denominator: 9 });
});
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-6-ijhun?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-6-solution-f7n


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)