DEV Community

Nicolas DUBIEN
Nicolas DUBIEN

Posted on • Updated on

Advent of PBT 2021 - Day 5

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

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

/**
 * You're given a message where spaces have been removed.
 * Your aim is to find back the original message given a dictionary
 * containing all the words. As many messages could be encoded the
 * same way, you may have to return two or more messages. No specific
 * ordering is expected when multiple solutions are available but all
 * must be returned.
 *
 * @param spacelessMessage - Message without any spaces
 * @param words - List of accepted words (no repeat and at least one
 * character long)
 *
 * @returns
 * All the possible messages made only with the received words that
 * could have led to this spacelessMessage.
 */
declare function respace(spacelessMessage: string, words: string[]): string[];
Enter fullscreen mode Exit fullscreen mode

We already wrote some examples based tests for it:

it("should be able to detect one match when there is only one", () => {
  const out = respace("helloworld", ["hello", "world"]);
  expect(out).toEqual(["hello world"]);
});

it("should not detect any match and produce empty arrays when no matchs", () => {
  const out = respace("hellowooorld", ["hello", "world"]);
  expect(out).toEqual([]);
});

it("should be able to detect all the matches when multiple are eligible", () => {
  const out = respace("tititi", ["ti", "titi"]);
  expect(sorted(out)).toEqual(["ti ti ti", "ti titi", "titi ti"]);
});
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-5-6ekxo?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-5-solution-6e2


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)