Testing
Test your Motia Backend System - APIs, Events
You built an API. You added some event handlers. Everything seems to work. But does it?
Without tests, you're guessing. With tests, you know.
Motia has @motiadev/test built in. It helps you:
- Test API triggers (hit endpoints, check responses)
- Test Event triggers (verify events get emitted)
- Mock contexts for unit tests
Install
Test API Triggers
Here's an API Step that creates a todo and emits an event:
Now let's test it:
What's happening here:
createMotiaTester()→ Spins up a test version of your apptester.post()→ Hits your API like a real client wouldtester.watch()→ Captures events that get emittedtester.waitEvents()→ Waits for all async stuff to finish- Then check if everything worked
Test Event Triggers
Event Steps listen for events and do stuff in the background. Here's how to test them:
The Test:
👉 Use tester.emit() to manually fire events and test Event triggers without hitting APIs.
Unit Test Handlers
Don't want to spin up the whole app? Test handler functions directly:
Run Your Tests
All tests:
Watch mode (re-runs when you save files):
Single test file:
Tester API
createMotiaTester()
Starts a test version of your app.
What you can do with it:
| Method | What it does |
|---|---|
post(path, options) | Hit a POST endpoint |
get(path, options) | Hit a GET endpoint |
emit(event) | Fire an event manually |
watch(topic) | Catch events on a topic |
waitEvents() | Wait for events to finish |
sleep(ms) | Pause for X milliseconds |
close() | Shut down the tester |
createMockContext()
Mock a context for testing handlers directly.
You get:
logger- Mock logger (Jest spy)emit- Mock emit (Jest spy)traceId- Request trace IDstate- Mock state manager
Tips
- ✅ Start simple - Test basic stuff first, then edge cases
- ✅ Test errors - Make sure your error handling actually works
- ✅ Watch events - Don't assume events fired, check them
- ✅ Always wait - Call
waitEvents()or events might not finish - ✅ Clean up - Always
close()the tester when done - ✅ Keep it isolated - Each test should work on its own
- ✅ Name tests well - Say what you're checking, not how