dimanche 5 juin 2016

WP_Ajax_UnitTestCase does not throw WPAjaxDieStopException

Ok so I am testing my ajax callbacks for my wordpress plugin. So I basically followed instructions here http://ift.tt/1PcKdFm

Here is my ajax callback function

public function my_plugin_get_site_pages( $args = null ) {

  //...... Processing $site_pages.....

  $response = array(
   'status'     => 'success',
   'site_pages' => $site_pages
  );

  @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
  echo wp_json_encode( $response );
  wp_die();

}

Here is my test

class My_Plugin_Ajax_Test extends WP_Ajax_UnitTestCase {

  private $_foo;

  public function setup() {

    //.....Initialize $_foo here...

  }

  public function test_foo() {

    try {

        $_POST[ 'args' ] = array( 'return_format' => 'raw' );

        add_action( 'wp_ajax_my_plugin_get_site_pages' , array( $this->_foo , 'my_plugin_get_site_pages' ) );

        //$this->setExpectedException( 'WPAjaxDieStopException' );
        $this->_handleAjax( 'my_plugin_get_site_pages' );

    } catch ( WPAjaxDieStopException $e ) {}

    //$response = json_decode( $this->_last_response );
    $response = $this->_last_response;
    var_dump( $response );

  }

}

Now here are the issues

  1. It doesn't throw WPAjaxDieStopException exception like its suppose to

when I do this code $this->setExpectedException( 'WPAjaxDieStopException' ); it fails the test http://ift.tt/1WAICRr

  1. It prints out that wp_die() has been triggered, so this code

$response = $this->_last_response; var_dump( $response );

prints this

http://ift.tt/1PcKnfY

Number 2 is an issue because you cannot do json_decode the string outputted coz its an invalid json string, so I can't continue with my test.

I'm just starting out with automated testing on wordpress plugins and I appreciate any help.

Note: My ajax callback is working ok on my live plugin even if I use wp_die(), it just prints that weird 'wp_die called ...' string on my test.

My php version is 5.6.21 and my phpunit version is 4.8.26



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire