DEV Community

Nicolas DUBIEN
Nicolas DUBIEN

Posted on • Edited on

3 2

Advent of PBT 2021 - Day 12

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

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

/**
 * Given a string s containing just the characters '(', ')', '{',
 * '}', '[' and ']', determine if the input string is valid.
 *
 * @param expression -
 *
 * @returns
 * An input string is valid if:
 * Open brackets must be closed by the same type of brackets.
 * Open brackets must be closed in the correct order.
 */
declare function validParentheses(expression: string): boolean;
Enter fullscreen mode Exit fullscreen mode

We already wrote some examples based tests for it:

it("should accept simple expressions", () => {
  expect(validParentheses("[]")).toBe(true);
});

it("should accept nested expressions", () => {
  expect(validParentheses("[({})]")).toBe(true);
});

it("should accept expressions with multiple groups", () => {
  expect(validParentheses("[({})][]([])")).toBe(true);
});

it("should reject wrong matching bracket", () => {
  expect(validParentheses("[)")).toBe(false);
});

it("should reject unbalanced brackets with more closing", () => {
  expect(validParentheses("[]()}")).toBe(false);
});

it("should reject unbalanced brackets with more opening", () => {
  expect(validParentheses("[](){")).toBe(false);
});

it("should reject bad nesting", () => {
  expect(validParentheses("[(])")).toBe(false);
});
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-12-fjifg?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-12-solution-3oic


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)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay