DEV Community


Posted on

TDD and Publish-Subscribe pattern implementation via TDD

My understanding of TDD

TDD is a practice that follows red-green-refactor circles:

  1. Red: write a minimal and straightforward test first, one at a time. The test fails hence the name 'red', because the code is not written yet.
  2. Green: write just enough code to get the test, be it a shortcut that doesn't make any business sense, for example, hard coding a string. The aim here is to get the test to pass i.e. turning green.
  3. Refactor: refactor both tests and code and keep the test green
  4. Repeat with more tests, one at a time, as simple as possible, edging closer to the business requirements

TDD requires an accurate understanding of business requirements. TDD is the process of constantly expressing business requirements in the form of tests, one small step at a time.

TDD is the ultimate weapon for highly maintainable software. However, from what I learned so far, it is not practical to apply TDD to all codes or you will get burned and give up.

The most effective way is to separate the business logic from other noises to become an input/output based structure. TDD the business logic.

Testing is hard. Sticking to testing is all about forcing ourselves to design our code in such a way that testing is not hard anymore. It is the design that is hard.

What is publish-subscribe pattern

Definition from Wikipedia:

publish–subscribe is a messaging pattern where senders of messages, called publishers, do not program the messages to be sent directly to specific receivers, called subscribers, but instead categorize published messages into classes without knowledge of which subscribers, if any, there may be.

Similarly, subscribers express interest in one or more classes and only receive messages that are of interest, without knowledge of which publishers, if any, there are.

The essence of the pattern is the decoupling of publishers and subscribers.

This blog post will show an attempt to implement a topic-based publish-subscribe pattern using Typescript and Jest.


  1. publishers can send messages with a topic and payload
  2. subscribers can subscribe to any topics and provide a call back function
  3. subscribers' call back function gets called with the payload if any publishers publish any of the subscribed topics


Publishers and subscribers do not know the existence of each other


Top comments (0)