• Jack

    (@jack1132132)


    Hello,

    I’ve stumbled upon a big hurdle in phpunit for wordpress, where I can’t call _handleAjax more than once in a test. I have to call it at most once in a test otherwise I encounter issues.

    My test file is as follows:

    
    class AjaxTest extends WP_Ajax_UnitTestCase {
    
            public function test_submission_verification() {
    
    		global $_POST;
    		$_POST['directory_id'] = 'ded88';
    		$_POST['page'] = '1';
    		$_POST['sorting'] = 'random';
    		$_POST['gmt_offset'] = '0';
    		$_POST['post_refferer'] = '53';
    		$_POST['nonce'] = wp_create_nonce( 'um-frontend-nonce' );
    		$_POST['action'] = 'um_get_members';
    		try {
    			$this->_handleAjax( 'um_get_members' );
    		} catch ( WPAjaxDieStopException | WPAjaxDieContinueException $e ) {
                            // We expected this, do nothing.
                    }
                    //so far so good
                    try {
    			$this->_handleAjax( 'um_get_members' );
    		} catch ( WPAjaxDieStopException | WPAjaxDieContinueException $e ) {
                            // We expected this, do nothing.
                    }
    		//mayhem
    	}
    }			

    I’ve looked at the code inside the WP_Ajax_UnitTestCase class and it seems _handleAjax is built to be called once in a test and thats it:

    protected function _handleAjax( $action ) {
    
    		// Start output buffering.
    		ini_set( 'implicit_flush', false );
    		ob_start();
    
    		// Build the request.
    		$_POST['action'] = $action;
    		$_GET['action']  = $action;
    		$_REQUEST        = array_merge( $_POST, $_GET );
    
    		// Call the hooks.
    		do_action( 'admin_init' );
    		do_action( 'wp_ajax_' . $_REQUEST['action'], null );
    
    		// Save the output.
    		$buffer = ob_get_clean();
    		if ( ! empty( $buffer ) ) {
    			$this->_last_response = $buffer;
    		}
    	}

    So I’ve tried removing do_action( 'admin_init' ); from the function but unfortunately there’s still problems.

    Issue is that for these phpunit tests wordpress is bootstrapped and setup for each test and I cant re-boostrap it in the middle of a test so changes made to classes and global functions remain throughout the test. I’ve tried doing $this->tear_down() ; $this->set_up() ; but those functions can only do so much.

    Is there any way to get around this, how can I make multiple ajax calls to in one test function?

    Thank you.

    UPDATE: _handleAjax cant be called more than once in different tests from different files even.

    • This topic was modified 1 year, 3 months ago by Jack.
    • This topic was modified 1 year, 3 months ago by Jack.
    • This topic was modified 1 year, 3 months ago by Jack.
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘Phpunit: making multiple ajax calls in one test’ is closed to new replies.