I’ve asked this on IRC, Twitter, Slack — am utterly astonished by how difficult it is to locate the answer to this:
I have a bunch of plugin code that only runs when is_admin()
returns true
, i.e., when the user is looking at the admin panel.
How do I arrange a unit test such that it’s in the admin context when the assertions are run?
1
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();
}
}