Events API
Codeception Events API is, but, only available to Modules and Extensions, and while that might be good for most cases, it might not cover a number of edge cases.
Similarly to WordPress
add_action
function, wp-browser
provides the tad\WPBrowser\addListener
function:function addListener($eventName, callable $listener, $priority = 0);
The priority works the reverse way as it does in WordPress: highest number will be processed first!
Again similarly to WordPress
do_action
function, the tad\WPBrowser\dispatch
function:function dispatch($eventName, $origin = null, array $context = []);
This is the kind of API that is better shown with an example, though.
In this example I'm writing acceptance tests and would like to avoid the performance hit that the
cleanup
configuration parameter of the Db
, or WPDb
, module implies.
The cleanup
parameter will trigger the drop of all tables in the test database and the re-import of the SQL dump file, or files, between each test.
This will ensure a clean starting fixture between tests, but for larger setup fixtures this might be a long operation that wastes precious seconds when, say, the only change is the addition of 3 posts, as in this example.The Events API allows implementing a tailored clean-up procedure that can avoid costly clean ups between tests.
In the suite bootstrap file, e.g.
tests/acceptance/_bootstrap.php
, I add a listener on the my-plugin-test/setup-posts
event.
The event will contain information about what post IDs I've set up in the tests and will provide an instance of the tester object to handle database manipulation.
With that information, the costly cleanup
procedure can be avoided.<?php