DEV Community

Nicolas DUBIEN
Nicolas DUBIEN

Posted on • Edited on

Advent of PBT 2021 - Day 23

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

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

/**
 * Each year, Santa receives wish lists coming from everywhere.
 *
 * Lists are ordered starting by the most important present to the last
 * important one. Santa does not always offer the most important one.
 * From time to time he wants to wait one more year to check if the
 * present stays in the top.
 *
 * Each year, Santa manually performs a diff of the list with
 * the one of the year before. Based on this diff he makes his choice.
 *
 * You can see the diff manually computed by Santa as an usual git diff
 * between two strings including many lines.
 *
 * Let's take the example:
 *
 *   Year N:
 *     Cars
 *     Trains
 *     Planes
 *
 *   Year N+1:
 *     Cars
 *     Buses
 *     Trains
 *     Boats
 *
 *   Diff of Santa:
 *     === Cars
 *     +++ Buses
 *     === Trains
 *     +++ Boats
 *     --- Planes
 *
 * @param before - String representing the list of presents (before)
 * @param after - String representing the list of presents (after)
 */
declare function wishListsDiffer(before: string, after: string): string;
Enter fullscreen mode Exit fullscreen mode

We already wrote some examples based tests for it:

it("should compute the appropriate diff", () => {
  // Arrange
  const previousYear = "Cars\nTrains\nPlanes";
  const currentYear = "Cars\nBuses\nTrains\nBoats";

  // Act
  const diff = wishListsDiffer(previousYear, currentYear);

  // Assert
  // prettier-ignore
  expect(diff).toEqual(
    "=== Cars\n" +
    "+++ Buses\n" +
    "=== Trains\n" +
    "+++ Boats\n" +
    "--- Planes"
  );
});
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-23-q1468?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-23-solution-4lg4


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)