Advent of PBT 2021 — Learn how to use property based testing and fast-check through examples
Our algorithm today is: hasDuplicates.
It comes with the following documentation and prototype:
/**
* Check if an array contains two equal values
* Comparison operator in use is `Object.is`
*
* @param data - Array of data
*
* @returns
* `true` if `data` contains two values such as
* `Object.is(data[i], data[j])` is `true`
* `false` otherwise
*/
declare function hasDuplicates<T>(data: T[]): boolean;
We already wrote some examples based tests for it:
it("should not detect any duplicates in empty array", () => {
expect(hasDuplicates([])).toBe(false);
});
it("should not detect any duplicates when array has distinct values", () => {
expect(hasDuplicates([1, 2, 3, 4])).toBe(false);
});
it("should detect duplicate when array has one", () => {
expect(hasDuplicates([1, 2, 3, 1])).toBe(true);
});
it("should detect duplicate when array has many", () => {
expect(hasDuplicates([1, 2, 2, 1, 3])).toBe(true);
});
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-8-2nziy?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-8-solution-4c2j
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)