Sub topic 12
Testing event publishing and subscribers
This chapter shows how to write Apex and Jest tests for platform events. It assumes you can write Apex test classes with @IsTest, you know the Test.startTest() and Test.stopTest() pattern, and you have read the chapters on publishing with EventBus.publish and subscribing with an Apex trigger. The examples use the Order_Shipped__e event from earlier chapters.
Why event tests need extra care
A normal DML statement fires its triggers inside the same transaction, so a test can assert on the results on the next line. Platform events work differently. EventBus.publish only queues the event. The subscriber trigger runs later, in its own transaction. A test that publishes an event and immediately queries for the trigger's output will find nothing.
Salesforce gives tests two ways to deliver queued events on demand:
Test.stopTest()delivers every event published sinceTest.startTest().Test.getEventBus().deliver()delivers the events published so far and lets the test keep running.
After either call, subscriber triggers have run, and the test can assert on their results.
Testing a publisher
A publisher test has two jobs: confirm that the publish call succeeded, and confirm that the event was sent when the business logic says it should be. The first job uses the SaveResult.
@IsTest
private class OrderShippedPublishTest {
@IsTest
static void publishReturnsSuccess() {
Order_Shipped__e evt = new Order_Shipped__e(
Order_Number__c = '00012345',
Status__c = 'Shipped'
);
Test.startTest();
Database.SaveResult sr = EventBus.publish(evt);
Test.stopTest();
Assert.isTrue(sr.isSuccess(), 'The event should be queued for publishing');
}
}isSuccess() being true means Salesforce accepted the event for publishing. It does not mean any subscriber has processed it.
To test the failure path, publish an event that breaks a rule. For example, if Order_Number__c is marked required, publishing an event without it returns a failed result:
@IsTest
static void publishFailsWhenRequiredFieldIsMissing() {
Test.startTest();
Database.SaveResult sr = EventBus.publish(new Order_Shipped__e(Status__c = 'Shipped'));
Test.stopTest();
Assert.isFalse(sr.isSuccess());
Assert.isFalse(sr.getErrors().isEmpty());
}Check your own error-handling code the same way. If a class logs or rethrows when isSuccess() is false, this test is the only cheap way to run that branch.
Testing code that publishes as a side effect
Most real publishers are not called directly. A service class or trigger publishes after some other work. In that case the test runs the business action and then checks the outcome of the event, not the event itself.
An event cannot be reliably read back with a query in a test. Verify the effect of delivery instead. You can assert on records a subscriber creates. If the subscriber is a separate component, you can also assert on the value returned by EventBus.publish, as long as your service class exposes it.
Testing a subscriber trigger
The subscriber test publishes real events and lets the platform deliver them to the trigger. The trigger from the earlier chapter creates one Task per event:
@IsTest
private class OrderShippedTriggerTest {
@IsTest
static void createsOneTaskPerEvent() {
Test.startTest();
EventBus.publish(new Order_Shipped__e(Order_Number__c = '00012345', Status__c = 'Shipped'));
Test.stopTest();
List<Task> tasks = [SELECT Subject, Status FROM Task];
Assert.areEqual(1, tasks.size());
Assert.areEqual('Follow up on order 00012345', tasks[0].Subject);
Assert.areEqual('Not Started', tasks[0].Status);
}
}Test bulk delivery
A trigger receives events in batches, so a test that publishes only one event misses the bulk bugs. Publish a list instead:
@IsTest
static void handlesLargeBatch() {
List<Order_Shipped__e> events = new List<Order_Shipped__e>();
for (Integer i = 0; i < 200; i++) {
events.add(new Order_Shipped__e(
Order_Number__c = String.valueOf(10000 + i),
Status__c = 'Shipped'
));
}
Test.startTest();
List<Database.SaveResult> results = EventBus.publish(events);
Test.stopTest();
for (Database.SaveResult sr : results) {
Assert.isTrue(sr.isSuccess());
}
Assert.areEqual(200, [SELECT COUNT() FROM Task]);
}A trigger that runs DML or SOQL inside the for loop passes the single-event test and fails this one with a governor limit error.
Deliver in the middle of a test
Test.stopTest() ends the test context. If you need to check state after delivery and then do more work, use deliver():
@IsTest
static void deliversEventsMidTest() {
EventBus.publish(new Order_Shipped__e(Order_Number__c = '1', Status__c = 'Shipped'));
Test.getEventBus().deliver();
Assert.areEqual(1, [SELECT COUNT() FROM Task]);
EventBus.publish(new Order_Shipped__e(Order_Number__c = '2', Status__c = 'Shipped'));
Test.getEventBus().deliver();
Assert.areEqual(2, [SELECT COUNT() FROM Task]);
}Use this when you need to prove that two events published at different times both get processed.
Separate the logic from the trigger
A trigger is hard to test in isolation because delivery goes through the event bus. A common pattern is to keep the trigger thin and move the work into a handler class. The handler receives a plain list of events, so tests can call it directly without publishing anything.
public with sharing class OrderShippedHandler {
public static List<Task> buildTasks(List<Order_Shipped__e> events) {
List<Task> tasks = new List<Task>();
for (Order_Shipped__e evt : events) {
tasks.add(new Task(
Subject = 'Follow up on order ' + evt.Order_Number__c,
Status = 'Not Started'
));
}
return tasks;
}
}trigger OrderShippedTrigger on Order_Shipped__e (after insert) {
insert OrderShippedHandler.buildTasks(Trigger.new);
}@IsTest
static void buildTasksMapsEachEvent() {
List<Order_Shipped__e> events = new List<Order_Shipped__e>{
new Order_Shipped__e(Order_Number__c = 'A1'),
new Order_Shipped__e(Order_Number__c = 'A2')
};
List<Task> tasks = OrderShippedHandler.buildTasks(events);
Assert.areEqual(2, tasks.size());
Assert.areEqual('Follow up on order A2', tasks[1].Subject);
}An event object created with new and never published is just an in-memory sObject. This test needs no delivery, so it runs fast and can use any input, including edge cases such as a null field. Keep one or two end-to-end tests with stopTest() to prove the trigger is wired to the handler.
Testing a subscriber that retries
A trigger that throws EventBus.RetryableException is retried in production. Test the paths you control: the code that decides whether to throw, and the code that sets the resume checkpoint. Put that decision in the handler where possible, so a plain unit test can verify that bad input leads to the exception. Then check the retry behavior itself in a sandbox, because test-context behavior may differ from production delivery.
Testing a Lightning Web Component subscriber
Apex tests do not cover empApi. The component runs in the browser, so use Jest with @salesforce/sfdx-lwc-jest. Replace lightning/empApi with a mock, capture the callback the component passes to subscribe, and call it with a fake message.
import { createElement } from 'lwc';
import OrderShippedListener from 'c/orderShippedListener';
import { subscribe, unsubscribe } from 'lightning/empApi';
jest.mock(
'lightning/empApi',
() => ({
subscribe: jest.fn(),
unsubscribe: jest.fn(),
onError: jest.fn()
}),
{ virtual: true }
);
const flushPromises = () => Promise.resolve();
describe('c-order-shipped-listener', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
jest.clearAllMocks();
});
it('subscribes to the event channel with replay ID -1', () => {
subscribe.mockResolvedValue({ id: 'sub-1', channel: '/event/Order_Shipped__e' });
const element = createElement('c-order-shipped-listener', { is: OrderShippedListener });
document.body.appendChild(element);
expect(subscribe).toHaveBeenCalledWith('/event/Order_Shipped__e', -1, expect.any(Function));
});
it('reads the payload from a received message', async () => {
subscribe.mockResolvedValue({ id: 'sub-1' });
const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
const element = createElement('c-order-shipped-listener', { is: OrderShippedListener });
document.body.appendChild(element);
const callback = subscribe.mock.calls[0][2];
callback({ data: { payload: { Order_Number__c: '00012345' } } });
expect(logSpy).toHaveBeenCalledWith('Order shipped: 00012345');
logSpy.mockRestore();
});
it('unsubscribes when removed from the page', async () => {
subscribe.mockResolvedValue({ id: 'sub-1' });
const element = createElement('c-order-shipped-listener', { is: OrderShippedListener });
document.body.appendChild(element);
await flushPromises();
document.body.removeChild(element);
expect(unsubscribe).toHaveBeenCalledWith({ id: 'sub-1' }, expect.any(Function));
});
});The await flushPromises() line matters in the last test. The component stores the subscription inside a .then(), so the test must let that promise settle before it removes the element.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Asserting before `stopTest()` or `deliver()` | Query returns no records | Move assertions after delivery |
| Publishing outside `startTest`/`stopTest` and never delivering | Trigger never runs in the test | Wrap the publish or call `deliver()` |
| Testing only one event | Bulk bugs reach production | Publish 200 events |
| Checking only `isSuccess()` | Subscriber bugs go unnoticed | Assert on the subscriber's records |
| Not waiting for promises in Jest | `unsubscribe` assertion fails | Flush promises after mounting |
Exercise
A test publishes an Order_Shipped__e event and then immediately runs [SELECT COUNT() FROM Task] before calling Test.stopTest(). The count is 0 even though the trigger is correct. Why, and what are two ways to fix the test?
Show answer
Publishing only queues the event, and the subscriber trigger runs in a separate transaction when the event is delivered. Nothing has been delivered at the time of the query. Fix it by running the query after Test.stopTest(), which delivers the events published since Test.startTest(). Or call Test.getEventBus().deliver() after publishing and before the query.
Exercise
Why should a subscriber trigger test publish a list of about 200 events, and what kind of bug does it expose that a one-event test does not?
Show answer
A trigger receives events in batches in Trigger.new. Publishing many events checks that the code is bulk-safe. Code that runs SOQL or DML inside the loop passes with one event but exceeds governor limits with a large batch.