Advent of PBT 2021 — Learn how to use property based testing and fast-check through examples
Our algorithm today is: lastIndexOf.
It comes with the following documentation and prototype:
/**
* Check whether a pattern is contained within a text.
* If so, where does it starts.
*
* @param search - The substring to search for in the string
* @param text - The string where we should look for the substring
*
* @returns
* The last index of pattern in text.
*/
declare function lastIndexOf(search: string, text: string): number;
We already wrote some examples based tests for it:
it('should return -1 when there is no match at all', () => {
expect(lastIndexOf('abc', 'defghi')).toBe(-1);
});
it('should return -1 when match is not complete', () => {
expect(lastIndexOf('abc', 'abdefghi')).toBe(-1);
});
it('should return the start index of the match', () => {
expect(lastIndexOf('cdef', 'abcdefghi')).toBe(2);
});
it('should return the start index of the last match', () => {
expect(lastIndexOf('cdef', 'abcdefghiabcdefghi')).toBe(11);
});
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-1-3ewqs?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-1-solution-1l5l
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)