I am trying to unit test the function I’m using in a theme to register sidebars.
Here is the function from functions.php.
function fp_register_sidebars() {
register_sidebar( array(
'name' => __( 'Sidebar 1', 'fp' ),
'id' => 'sidebar1',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
) );
register_sidebar( array(
'name' => __( 'Sidebar 2', 'fp' ),
'id' => 'sidebar2',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h4 class="widget-title">',
'after_title' => '</h4>'
) );
}
add_action( 'widgets_init', 'fp_register_sidebars' );
Here is the unit test method.
function test_fp_register_sidebars() {
do_action( 'widgets_init' ); // Run the widgets_init hook
/** @var array $sidebars Array containing all active sidebars and their widgets. */
$sidebars = wp_get_sidebars_widgets();
$this->assertTrue( array_key_exists( 'sidebar1', $sidebars ), 'Sidebar 1 is registered at the widgets_init hook.' );
$this->assertTrue( array_key_exists( 'sidebar2', $sidebars ), 'Sidebar 2 is registered at the widgets_init_hook.' );
}
The unit test fails. Looking into this I found that the sidebars are not being updated from the sidebars for twentythirteen to the sidebars for this theme (they stay at sidebar-1 and sidebar-2). I’m switching to my theme in the unit test class setUp() method using switch_theme() and that is successful.
Activating the theme on a WordPress environment does correctly register these sidebars so I’m thinking it is something to do with how switch_theme() works.