How to unit test a service which output is an event with data?
https://softwareengineering.stackexchange.com/questions/399504
-
03-03-2021 - |
Question
Technologies : NodeJs, Kafka, Mocha
The issue : I have a nodeJS service which given a String returns events with a many data.
How can I test this using Mocha ?
In a simple scenario the service returns one event with some data attached. In a more complex scenario the service publishes multiple events.
Is there a way I can test the services output at unit test level?
Possible solutions : A solution I can think of is to create a consumer inside the mocha test. Is there another practice/method I can follow ? Should I test this at a different level aka integration level ?
Solution
I haven't done extensive unit testing in java script. But the principles remain fairly same in all the languages.
Properties of a good unit test would be
- Runs quickly and provides nearly immediate feedback
- Doesn't have side effects, like charging a credit card, or modifying a database or event publishing an event
What needs to be tested in your case
- Is it publishing the event in the needed scenario
- Is it publishing the event with the correct values
Suggested design
- Design a "Event Publisher" object that is publishes the given event (string) to the broker
- Design the service to use the "Event Publisher"
- Inject the event publisher in the service when creating the service
- Create a "Mock Event Publisher" that is having the same method as "Event Publisher". But instead of publishing the message, it records the message published using it. Add a method to verify the messages published in the "Mock Event Publisher".
- While testing inject the mock event publisher in to the service instead of event publisher, and verify if the correct message is published at the correct time.
Integration Tests
I wouldn't test the actual insertion of the event to the kafka broker in unit test. I would test this in integration test.