DEV Community

Nicolas DUBIEN
Nicolas DUBIEN

Posted on • Edited on

Advent of PBT 2021 - Day 10

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

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

/**
 * Compute the minimal number of changes to be applied onto stringA
 * to change it into stringB.
 * In other words: Compute the distance of Levenshtein between
 * two strings.
 *
 * @param stringA - The first string to be taken into account
 * @param stringB - The second string to be taken into account
 *
 * @returns
 * Minimal number of single-character edits (insertions, deletions or
 * substitutions) to be applied onto stringA to change it into
 * stringB.
 */
declare function minimalNumberOfChangesToBeOther(
  stringA: string,
  stringB: string
): number;
Enter fullscreen mode Exit fullscreen mode

We already wrote some examples based tests for it:

it("should not consider any change to move to same value", () => {
  const out = minimalNumberOfChangesToBeOther("azerty", "azerty");
  expect(out).toBe(0);
});

it("should properly handle added characters", () => {
  const out = minimalNumberOfChangesToBeOther("azerty", "0aze5rty9");
  expect(out).toBe(3); // add: 0, 5, 9
});

it("should properly handle removed characters", () => {
  const out = minimalNumberOfChangesToBeOther("0aze5rty9", "azerty");
  expect(out).toEqual(3); // remove: 0, 5, 9
});

it("should properly handle updated characters", () => {
  const out = minimalNumberOfChangesToBeOther("azerty", "AzERTy");
  expect(out).toEqual(4); // update: a->A, e->E, r->R, t->T
});

it("should properly handle mix of add/remove/update", () => {
  const out = minimalNumberOfChangesToBeOther("azerty", "0az1eRt");
  expect(out).toEqual(4); // add: 0, 1, remove: y, update: r->R
});
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-10-78utw?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-10-solution-3a3d


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)