Mock kafkajs using Jest manual mock
.
The purpose of this project is to run unit tests against a kafkajs
module mocked by Jest's manual mock. It compares with running unit tests against the actual kafkajs
module which requires a Kafka instance running (locally or remotely). It also compares with running unit tests against Jest function mock (A.K.A. stub
).
This project is tested in node.js v10.15.0 version. In the root directory, run
npm i
to install required node modules.
This project also requires Docker installed locally. To install Docker, follow the document.
npm run setup-local-env
npm run test-actual
npm run test-function-mock
npm run test-manual-mocks
- Testing with the real environment
- Don't need to mock return values for each test.
-
This usually takes long to complete the tests.
-
When consumer attempts to subscribe to a topic by calling
await consumer.subscribe({ topic });
it's possible to get error message There is no leader for this topic-partition as we are in the middle of a leadership election
. So subscription won't establish until Zookeeper finishes election.
-
In different test cases, if consumers subscribe to the same topic and share the same groupId, test cases might interfere one another. (especially when Jest runs them in parallel).
-
PR triggered tests/builds require Docker in the env, and takes longer to setup env (needs to download Kafka/Zookeeper images).
- Fast
- Flexible to mock return values for each tests.
- Tedious to setup tests
- Fast
- Don't need to mock return values for each test.
- One general mocked implementation can handle multiple situations.
- Need to implement a mock and test against it.
- The implementation of
kafkajs
module mocking is here. It's a simplekafkajs
module mock that runs in memory. It supports producers'connect
,send
, anddisconnect
methods. It also supports consumers'connect
,subscribe
,run
, anddisconnect
methods. It supports multiple consumers in the same group, or in different groups. - Batched message consuming has not been implemented.
- Since it's a local kafkajs implementation, it doesn't implement the concept of
partition
orbroker
.