We should create some testing tools/helpers in order to be more easily write tests for Moleculer services. E.g. mocking dependent services, waiting for emitted events, mocking broker.calls...etc
Detailed design
Creating broker for tests
createBroker is a helper which creates ServiceBroker instance for testing. It disables logger, add test middlewares & can register local mock services.
Base broker options which merged the passed options
Need a testing middleware which wraps the emit, broadcast & broadcastLocal methods & collect every call.
Register some asserting methods into ServiceBroker instance.
Summary
We should create some testing tools/helpers in order to be more easily write tests for Moleculer services. E.g. mocking dependent services, waiting for emitted events, mocking broker.calls...etc
Detailed design
Creating broker for tests
createBroker
is a helper which createsServiceBroker
instance for testing. It disables logger, add test middlewares & can register local mock services.Base broker options which merged the passed options
Create a tester broker instance with default options
Create broker with custom broker options
Create broker with options & mocked services
Collect & wait for events
Need a testing middleware which wraps the
emit
,broadcast
&broadcastLocal
methods & collect every call. Register some asserting methods intoServiceBroker
instance.Assertion methods
broker.test.eventEmitted("posts.updated")
broker.test.eventEmittedTimes("posts.updated")
broker.test.eventEmittedWithParams("posts.updated", { postID: 5 })
Wait for an emitted event
Mocking action calls
Need a testing middleware which wraps the
broker.call
method & collect every call. It can register mocked calls, as well. Mock functionsbroker.test.mockAction("users.get")
.withParams({ id: 5 })
.withMeta({})
.returnValue({ id: 5, name: "John", email: "john@moleculer.services" });
Assertion methods
broker.test.actionCalled("users.get")
broker.test.actionCalledTimes("users.get")
broker.test.actionCalledWithParams("users.get", { id: 5 })