Writing a unit test for add_menu_page
-
23-02-2021 - |
سؤال
I am writing a few unit tests for a plugin that I have developed. However I seem to be hung up on testing one (seemingly) simple piece of code.
In the plugin I've written I have registered an admin menu page:
add_menu_page(
esc_html__( 'Places', 'wp-places' ),
esc_html__( 'Places', 'wp-places' ),
'manage_options',
'wp-places',
[ $this, 'places_page' ],
);
But I can't seem to come up with a unit test to ensure this menu item exists. I've seen a few uses of global $menu
, but when I check the global it isn't yet set.
Here is the very basics of what I have.
<?php
class AdminTests extends WP_UnitTestCase {
public function setUp() {
parent::setUp();
wp_set_current_user( self::factory()->user->create( [
'role' => 'administrator',
] ) );
$this->go_to( admin_url() );
}
public function test_admin_menu() {
global $menu;
print_r( $menu ); // not set
}
}
المحلول
Rather than worrying about the internal implementation of the menu code and the globals that it uses (there are several beside $menu
), I'd use a function like menu_page_url()
to check if the page exists. That function will return the URL if the menu is registered, or an empty string if it is not. So you could do:
$this->assertNotEmpty( menu_page_url( 'my_menu_slug' ) );
Additionally, you are not setting up the test correctly. The go_to()
method only sets up the main WP_Query
object, it doesn't work for admin URLs. You need to instead call your function that registers the admin menu. So your test would look something more like this:
class AdminTests extends WP_UnitTestCase {
public function setUp() {
parent::setUp();
wp_set_current_user( self::factory()->user->create( [
'role' => 'administrator',
] ) );
}
public function test_admin_menu() {
my_admin_menu_registration_func();
$this->assertNotEmpty( menu_page_url( 'my_menu_slug' ) );
}
}