DEV Community 👩‍💻👨‍💻

Nicolas DUBIEN
Nicolas DUBIEN

Posted on • Updated on

Advent of PBT 2021 - Day 20

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

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

/**
 * Draw a tree with:
 * - a trunc made of '^',
 * - leaves on the left made of '('
 * - and the ones on the right made of ')'
 *
 * @param size - Size of the tree >=1
 */
declare function drawTree(size: number): string;
Enter fullscreen mode Exit fullscreen mode

We already wrote some examples based tests for it:

it("should be able to draw a tree of size 1", () => {
  // prettier-ignore
  expect(drawTree(1)).toEqual(
    "^\n" +
    "^\n" +
    "^"
  );
});

it("should be able to draw a tree of size 2", () => {
  // prettier-ignore
  expect(drawTree(2)).toEqual(
    " ^\n" +
    "(^)\n" +
    " ^\n" +
    " ^"
  );
});

it("should be able to draw a tree of size 5", () => {
  // prettier-ignore
  expect(drawTree(5)).toEqual(
    "    ^\n" +
    "   (^)\n" +
    "  ((^))\n" +
    " (((^)))\n" +
    "((((^))))\n" +
    "    ^\n" +
    "    ^"
  );
});
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-20-61ylb?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-20-solution-43nm


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)

Find and follow new tags! 🤔 Did you know?   DEV has a variety of tags to help you find the content you like. Find and follow your favorite tags