Unit testing in the WordPress backend (is_admin() is true)

According to this test, you use set_current_screen() to navigate to one of these in the setUp method.

Alas, none of this is apparent if you look at the tremendously-helpful reference page for get_current_screen()

Example:

<?php
class AxisSetupTest extends WP_UnitTestCase {    
    /**
     * @covers AxisWP::__construct
     */
    function test_constructor() {
        // Assert

        // Admin
        $this->assertInternalType('integer', has_action( 'admin_enqueue_scripts', array( 'AxisWP', 'add_admin_stylesheet' ) ) );
    }


    public function setUp() {
            parent::setUp();

            $user_id = $this->factory->user->create( array( 'role' => 'administrator' ) );
            $user = wp_set_current_user( $user_id );

            // This is the key here.
            set_current_screen( 'edit-post' );
    }

    public function tearDown() {
            parent::tearDown();
    }
}

Leave a Comment