DEV Community

Nicolas DUBIEN
Nicolas DUBIEN

Posted on • Updated on

Advent of PBT 2021 - Day 14

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

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

/**
 * Re-order multiple tabs at the same time and relatively to others
 * (as browsers do).
 * 
 * In modern browsers including Mozilla Firefox or Google Chrome,
 * users can easily select N non-contiguous tabs at the same time
 * and reorder them in a single move.
 * 
 * For instance if you have the tabs, A, B, C, D and E
 * you can select A and C and move them after D
 * to get B, D, A, C and E.
 *
 * @param tabs - The original set of tabs of the browser
 * @param selectedTabs - The tab currently being moved, a subarray
 *                       of tabs
 * @param moveBeforeTab - One of the tabs oftabs but not of
 *                        selectedTabs taken as a reference
 *                        for the dropping place
 *
 * @returns
 * New tabs configuration after the drop.
 */
export function reorderTabs(
  tabs: number[],
  selectedTabs: number[],
  moveBeforeTab: number
): number[]
Enter fullscreen mode Exit fullscreen mode

We already wrote some examples based tests for it:

it("should be able to re-order one tab alone", () => {
  // Arrange
  const originalTabs = [0, 1, 2, 3, 4];
  const selectedTabs = [2];
  const moveTabsBefore = 4;

  // Act
  const reordered = reorderTabs(originalTabs, selectedTabs, moveTabsBefore);

  // Assert
  expect(reordered).toEqual([0, 1, 3, 2, 4]);
});

it("should be able to re-order many contiguous tabs", () => {
  // Arrange
  const originalTabs = [0, 1, 2, 3, 4];
  const selectedTabs = [0, 1];
  const moveTabsBefore = 4;

  // Act
  const reordered = reorderTabs(originalTabs, selectedTabs, moveTabsBefore);

  // Assert
  expect(reordered).toEqual([2, 3, 0, 1, 4]);
});

it("should be able to re-order many non-contiguous tabs", () => {
  // Arrange
  const originalTabs = [0, 1, 2, 3, 4];
  const selectedTabs = [0, 2];
  const moveTabsBefore = 4;

  // Act
  const reordered = reorderTabs(originalTabs, selectedTabs, moveTabsBefore);

  // Assert
  expect(reordered).toEqual([1, 3, 0, 2, 4]);
});
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-14-3g438?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-14-solution-577o


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)