![]() ![]() Pay attention at how the method is partially applied. Our original method is the same but instead of checking the hardcoded property name, it relies on the variable in the first arrow function. Our reviver is now a function receiving a key, which returns a function accepting a key,value and returns the transform value. Let's start by writing those individual methods: How can we get rid of the switch, split all those transformation into individual methods so that we can write individual unit tests for each of those ( of course string.toUpperCase() is very simple but maybe your specific needs are more complex - and you need to test many scenarios) and compose them accordingly in different JSON.parse circumstances? We have a big method, with a switch case and all implementations altogether! Not really unit testable, nor reusable. This is already enough to understand how revivers work.īut, honestly I don't quite like the way the reviver is written. If you run the test again you will have green results, the transformations are applied and the result matches the expectation you defined at the top. ) the property will be removed from the output! By returning nothing (which means, return void, or null What is very interesting to note is the Password case. Since we need to apply multiple transformations on different properties, we have a big Switch and apply the uppercasing, reverting and so on returning the new value in case of a transformation, or the same value for all other keys. That means that you can write a reviver to double every number you have in the json (like shown in the docs), not very useful though.Ī reviver methods accepts a Key and a Value - for each property /node of our JSON, our method will be invoked. Write tests before you even have the code you want to test.Īs we said, a Reviver is a simple function that transform the value of a specific property or type in a JSON. And yes, that's exactly the Test Driven Development approach. Assert that your result matches the expectations.īut I don't have any revivers yet!, you might think.Act, that means run your revivers while parsing the JSON object.Arrange you test, preparing a JSON file or stringifying an object and preparing the output that you expect.This is also what i did to play around with Revivers. Never take anything for granted, and always read the docs!.Īnyway, the documentation is concise and clear, and there are plenty of posts explaining how to use it, so I won't bore you to death going into details, rather i'd like to add some tips about how to use it in a slightly more flexible and reusable way. It's incredible how after so many years there are so many things that I should know.īut it is one of the aspect of our job that is fascinating. ![]() If a function, this prescribes how the value originally produced by parsing is transformed, before being returned. Enter fullscreen mode Exit fullscreen mode ![]()
0 Comments
Leave a Reply. |