DEV Community

Nicolas DUBIEN
Nicolas DUBIEN

Posted on • Updated on

Advent of PBT 2021 - Day 7

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

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

/**
 * Compute fibonacci of n
 *
 * @param n - Index within fibonacci sequence
 *
 * @returns
 * The value of F(n) where F is the fibonacci sequence.
 * F(n) = F(n-1) + F(n-2), with F(0) = 0n and F(1) = 1n.
 */
declare function fibonacci(n: number): bigint;
Enter fullscreen mode Exit fullscreen mode

We already wrote some examples based tests for it:

it("should return 0n for fibonacci(0)", () => {
  expect(fibonacci(0)).toBe(0n);
});

it("should return 1n for fibonacci(1)", () => {
  expect(fibonacci(1)).toBe(1n);
});

it("should return 1n for fibonacci(2)", () => {
  expect(fibonacci(1)).toBe(1n);
});

it("should return 5n for fibonacci(5)", () => {
  expect(fibonacci(5)).toBe(5n);
});

it("should return 55n for fibonacci(10)", () => {
  expect(fibonacci(10)).toBe(55n);
});
Enter fullscreen mode Exit fullscreen mode

More details about Fibonacci's numbers on https://en.wikipedia.org/wiki/Fibonacci_number.

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-7-er12e?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-7-solution-4lf3


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)