Writing the code
We'll start with my naive implementation.
This function finds each fieldPath:[value1,value2, ...]
pattern
in the filters
query param string and
replaces it with (fieldPath:value1 OR fieldPath:value2 OR ...)
.
It achieves this using regex to find matches. We then iterate
over our matches, extract the fieldPath
and the values
,
format them as required, and then replace the old value.
However, my code isn't passing our test cases. What's wrong?
We have a couple of options for deducing the issue:
- Read and reason about the code
- Launch the tests in debug mode
- Use
console.log
to output variables at different points of interest in the function.
However, there is another option. This is where TDD shines.
I am reasonably confident that most of the internal logic of this component is correct. There is some small bug somewhere that I need to catch and fix. Instead of spending hours trying to find it, we will break the function up into smaller chunks with their own set of tests. This allows us to narrow down our search by confirming which parts of the code are doing what we want.
Here is our revised function:
Note we are now using the additional functions _getFieldPath
,
_getValues
, and _replaceValues
but we haven't defined them
yet. That's because we are going to use TDD for these functions, too.
I know what I expect these functions to be called with and what I expect them to output. And so, I write tests to validate that behavior. Here are some sample tests:
Our regex pattern is pretty complicated as well, so we will define a test for that, too:
These are important ins & outs for the behavior of our function. By ensuring we pass these tests, our function should work exactly as designed.