I need to unit test the functionality of an event listener but I've never done it before and I can't seem to find an example anywhere about it. Does anyone have any suggestions on a good way to go about this?
You can test the event listener does its thing by instantiating the listener, then getting it to handle your event. // Create a listener instance. $listener = app()->make(YourListener::class); // or just app(YourListener::class) // Create an event instance.
An event listener is a procedure in JavaScript that waits for an event to occur. The simple example of an event is a user clicking the mouse or pressing a key on the keyboard.
You need to use some concrete event name like for example click - and click on browser page window - eg: window. addEventListener('click', function() { console. log("some_event triggered"); });
There's not much to it, construct the event listener, pass in a mock event, and test.
@Test
public void testEventListener() {
ActionListener subjectUnderTest = new MyActionListener();
ActionEvent mockEvent = mock(ActionEvent.class);
// Or just create a new ActionEvent, e.g. new ActionEvent();
// setup mock
subjectUnderTest.actionPerformed(mockEvent);
// validate
}
Problems can arise when you follow the standard patterns for creating event listeners, where you define an anonymous class that directly interacts with the containing class. However it shouldn't be hard to refactor such a class into its own full class, and pass in any dependencies to the constructor, rather than implicitly from the surrounding class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With