• Resolved David Aguilera

    (@davilera)


    I have a plugin that adds registers a few AJAX callbacks as follows:

    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
      // Hooks here. For instance:
      add_action( 'wp_ajax_david_example', 'david_example' );
    }//end if

    where david_example is:

    function david_example() {
      wp_send_json( 'Done!' );
    }//end david_example()

    Now I want to create a PHP Unit Test to check that all AJAX callbacks work as expected, so I create the following test in test-ajax.php:

    class SampleTest extends WP_Ajax_UnitTestCase {
    
      public function test_sample() {
    
        try {
          $this->_handleAjax( 'david_example' );
        } catch ( WPAjaxDieContinueException $e ) {
        }//end try
    
        $this->assertTrue( isset( $e ) );
        $this->assertEquals( '"Done!"', $e->_last_response );
    
      }//end test_sample()
    
    }//end class

    Unfortunately, this test doesn’t work because $this->assertTrue( isset( $e ) ) fails – $e is never set. As far as I know, this occurs because the plugin was initialized before the constant DOING_AJAX was set and, therefore, my AJAX callback was never registered.

    What am I doing wrong?

Viewing 1 replies (of 1 total)
  • Thread Starter David Aguilera

    (@davilera)

    I haven’t yet found the solution, but I think I know a possible workaround.

    All the AJAX hooks my plugins adds are encapsulated in a function. Therefore, I was able to modify the test as follows:

    class SampleTest extends WP_Ajax_UnitTestCase {
    
      public function test_sample() {
    
        require_once( '.../class-my-ajax-api.php' );
        $ajax = new My_Ajax_API();
        $ajax->register_ajax_callbacks();
    
        try {
          $this->_handleAjax( 'david_example' );
        } catch ( WPAjaxDieContinueException $e ) {
        }//end try
    
        $this->assertTrue( isset( $e ) );
        $this->assertEquals( '"Done!"', $e->_last_response );
    
      }//end test_sample()
    
    }//end class

    That is, before running the test itself, I simply make sure that AJAX callbacks are registered.

    I still think that there has to be a different solution to let WordPress know that all the tests I’m about to run are AJAX and, therefore, it should “load” the plugin in “AJAX mode”. But, in the meantime, this solution works quite good for me.

Viewing 1 replies (of 1 total)
  • The topic ‘PHP Unit Test a Plugin AJAX Functionality with WP_Ajax_UnitTestCase’ is closed to new replies.