DEV Community

Nicolas DUBIEN
Nicolas DUBIEN

Posted on • Updated on

Advent of PBT 2021 - Day 9

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

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

/**
 * Build a sorted version of the passed array by relying
 * on "<" comparison.
 *
 * @param tab - Original array to be sorted
 *
 * @returns
 * Sorted copy of the original array.
 */
declare function sorted<T>(tab: T[]): T[];
Enter fullscreen mode Exit fullscreen mode

We already wrote some examples based tests for it:

it("should keep sorted array sorted", () => {
  expect(sorted([1, 2, 3])).toEqual([1, 2, 3]);
});

it("should sort reverse-sorted array", () => {
  expect(sorted([3, 2, 1])).toEqual([1, 2, 3]);
});

it("should sort any array", () => {
  expect(sorted([5, 2, 3, 1, 8])).toEqual([1, 2, 3, 5, 8]);
});
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-9-mxzok?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-9-solution-58dp


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)