2 ms·
If you have a pair of functions for encoding/decoding "something" you can do a round-trip and test that you get the original input back out, e.g.: JSON.par
by ngruhn 1y ago
If you have a pair of functions for encoding/decoding "something" you can do a round-trip and test that you get the original input back out, e.g.:
JSON.parse(JSON.stringify(randomObject)) === randomObject
That often works. What also often works is generating the expected output and constructing the input from it. For example, a `stripPrefix` function that removes a known prefix from string, e.g. `stripPrefix("foo", "foobar") === "bar"`. Property test:
stripPrefix(randomPrefix, randomPrefix + randomSuffix) === randomSuffix
Note, we "go backwards" and generated the expected output `randomSuffix` directly and then construct the input from it `randomPrefix + randomSuffix`.
Reference implementation based properties also work very often. For example, we've been developing a JavaScript rich text editor. That requires a bunch of utility functions on DOM trees that are analogous to standard string functions. For example, on a standard string you can get a char at an index with `"foo bar".charAt(3)` and on a rich text DOM tree we would need something like `treeCharAt(<U><B>foo</B> bar</U>, 3)`. The string functions can serve as a reference implementation for the more complex tree functions:
treeCharAt(randomTree, randomIndex) === extractStringContent(randomTree).charAt(randomIndex)
The same can be done with all string functions like `slice`, `indexOf`, `trim`, ...