Last week I worked on a issue writing unit test for PathProcessor Block processor in react-chatbotify. Since I've been writing tests for my own project, it seemed on brand to write a test. Although the project is in TS, it can be difficult to write unit test for a component that you are unfamiliar with.
Read The Code
So the first step was to read the code of PathProcessor.ts
. It handles processing of path in current block. takes three params, block an instance of Block
, params an instance of Params
and goToPath which is a function which takes a string. I saw there's two imports for Block
and Params
. So I checked the Block and Params type. Although Block
is a bit complex its not really used by PathProcessor aside from its one attribute. Next is params with relatively simple implementation. Although I don't understand the entire code, I just had to understand how these types work in respect to PathProcessor
. And the logic on PathProcessor
is relatively simple its just a sequence of guard clauses.
Writing The Test
I before writing the test I also took a look at previous PRs that are similar to mine. And the owner wants the only the logic of the component tested not everything that is used by it. So Basically I was testing all the logical paths of PathProcessor
. Based on the logic I would only need the path
attribute of block. As for params
I did not understand how it was being used so I mocked the entire object. I initially tired to mock only the needed attributes but I could not get all the tests to pass reliability. So, I did what I learned in my co-op that if the function is not the focus of the test just mock it. So that's what I did. While mocking I also followed how it was done in AudioService.test.ts
as recommended by the repo owner. And I followed the similar syntax. After a lot of trial and error I got 100% coverage.
Making PR
After I was able to finalize my code I made my PR. I noticed the repo owner uses conventionalcommits, so I adjusted my commit messages accordingly. And finally the PR was merged on the first try! This was definitely more difficult than the hacktoberfest issues. Reading and navigating the large code base to write the test was definitely challenging. But so far so good!
Top comments (0)