LoginSignup
7
5

More than 5 years have passed since last update.

admin_enqueue_scriptsフックで期待通りにjsやcssがロードされるかのテスト

Last updated at Posted at 2015-01-08

プラグイン側の処理

テストしたいコードは以下のような感じ。

wp-admin/post.phpまたはwp-admin/post-new.phpで、プラグイン独自のCSSやJavaScriptを読み込ませる。

wp-admin/post.phpwp-admin/post-new.php以外では読み込んでほしくない。

    /**
     * Fires on plugins_loaded hook.
     *
     * @param  none
     * @return none
     */
    public function plugins_loaded()
    {
        add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
    }

    /**
     * Fires on admin_enqueue_scripts hook
     *
     * @param  none
     * @return none
     */
    public function admin_enqueue_scripts( $hook_suffix )
    {
        /*
         * 管理画面のpost.phpまたはpost-new.phpでのみjavascript及びcssを追加
         */
        if ( 'post-new.php' === $hook_suffix || 'post.php' === $hook_suffix ) {
            wp_enqueue_script(
                'tinymce-templates',
                plugins_url( 'js/tinymce-templates.js', __FILE__ ),
                array( 'jquery' ),
                filemtime( dirname( __FILE__ ) . '/js/tinymce-templates.js' ),
                true
            );

            wp_enqueue_style(
                'tinymce-templates',
                plugins_url( 'css/tinymce-templates.css', __FILE__ ),
                array(),
                filemtime( dirname( __FILE__ ) . '/css/tinymce-templates.css' )
            );
        }
    }

PHPUnit用のテストコード

admin_enqueue_scriptsフックのコールバック関数を実行して、wp_style_is()wp_script_isでキューに保存されているかどうかをチェックする。

/**
 * @test
 */
function admin_enqueue_scripts()
{
    $tinymce_templates = new TinyMCE_Templates();

    /**
     * $hook_suffixがpost.phpでもpost-new.phpでもない
     * wp_style_is(), wp_script_is()ともにfalseであるべき
     */
    $tinymce_templates->admin_enqueue_scripts( '' );
    $this->assertFalse( wp_style_is( 'tinymce-templates' ) );
    $this->assertFalse( wp_script_is( 'tinymce-templates' ) );

    /**
     * $hook_suffixがpost.php
     * wp_style_is(), wp_script_is()ともにtrueであるべき
     */
    $tinymce_templates->admin_enqueue_scripts( 'post.php' );
    $this->assertTrue( wp_style_is( 'tinymce-templates' ) );
    $this->assertTrue( wp_script_is( 'tinymce-templates' ) );

    /**
     * $hook_suffixがpost-new.php
     * wp_style_is(), wp_script_is()ともにtrueであるべき
     */
    $tinymce_templates->admin_enqueue_scripts( 'post-new.php' );
    $this->assertTrue( wp_style_is( 'tinymce-templates' ) );
    $this->assertTrue( wp_script_is( 'tinymce-templates' ) );
}
7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5