Ajax Unit Tests for WordPress Plugin Development

The past couple of days I was having a hard time figuring out why my unit tests for AJAX were giving me an error stating Serialization of 'Closure' is not allowed. I’ve since fixed it and wanted to post about it because why not.

Things I installed:

  • wp scaffold plugin testplugin
  • composer require phpunit/phpunit ^9 --dev
  • composer require yoast/phpunit-polyfills --dev

This is the actual test class I was trying, saved to a testplugin/tests/test-ajax.php file.

 * Test cases for AJAX functions
 * @group ajax
 * @runTestsInSeparateProcesses
class AjaxTest extends WP_Ajax_UnitTestCase {
	public function setUp(): void
	public function testIsTrue(): void
		$this->assertTrue( true );
}Code language: PHP (php)

And here is the output when running the test.

./vendor/bin/phpunit --group ajax --debug --verbose
Running as single site... To run multisite, use -c tests/phpunit/multisite.xml
Not running ms-files tests. To execute these, use --group ms-files.
Not running external-http tests. To execute these, use --group external-http.
PHPUnit 9.5.24 #StandWithUkraine
Runtime:       PHP 8.0.22
Configuration: /var/www/test/wp-content/plugins/testplugin/phpunit.xml.dist
Serialization of 'Closure' is not allowedCode language: PHP (php)

I was following this article that mentions to use @runTestsInSeparateProcesses, because it tells PHPUnit to run each test from this class in a separate process”.

I’ve figured out that this annotation is what was causing the error. I’m not sure if it was because of the environment in which I was testing? I use Windows Subsystem for Linux for development while at work. But I don’t know how this really would affect it. I assume that it should have ran in a new process within WSL. Let me know if you know.

Here is my original StackExchange question, which I answered myself. https://wordpress.stackexchange.com/questions/409190




Leave a Reply

Your email address will not be published. Required fields are marked *