From baf225161eac7ecf2c2212b05512e5b3aef70033 Mon Sep 17 00:00:00 2001 From: Bernie Reiter Date: Tue, 30 May 2023 15:19:16 +0200 Subject: [PATCH] Comment Template Block: Add test coverage for context setting (#50879) Add a unit test to verify that the Comment Template block sets `commentId` context as expected. --- .../blocks/render-comment-template-test.php | 124 ++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 phpunit/blocks/render-comment-template-test.php diff --git a/phpunit/blocks/render-comment-template-test.php b/phpunit/blocks/render-comment-template-test.php new file mode 100644 index 00000000000000..500d3c7b665af6 --- /dev/null +++ b/phpunit/blocks/render-comment-template-test.php @@ -0,0 +1,124 @@ + $original_value ) { + update_option( $option, $original_value ); + } + + parent::tear_down(); + } + + public function set_up() { + parent::set_up(); + + update_option( 'page_comments', true ); + update_option( 'comments_per_page', self::$per_page ); + + self::$custom_post = self::factory()->post->create_and_get( + array( + 'post_type' => 'dogs', + 'post_status' => 'publish', + 'post_name' => 'metaldog', + 'post_title' => 'Metal Dog', + 'post_content' => 'Metal Dog content', + 'post_excerpt' => 'Metal Dog', + ) + ); + + self::$comment_ids = self::factory()->comment->create_post_comments( + self::$custom_post->ID, + 1, + array( + 'comment_author' => 'Test', + 'comment_author_email' => 'test@example.org', + 'comment_author_url' => 'http://example.com/author-url/', + 'comment_content' => 'Hello world', + ) + ); + } + + public function test_rendering_comment_template_sets_comment_id_context() { + $parsed_comment_author_name_block = parse_blocks( '' )[0]; + $comment_author_name_block = new WP_Block( + $parsed_comment_author_name_block, + array( + 'commentId' => self::$comment_ids[0], + ) + ); + $comment_author_name_block_markup = $comment_author_name_block->render(); + $this->assertNotEmpty( + $comment_author_name_block_markup, + 'Comment Author Name block rendered markup is empty.' + ); + + $render_block_callback = static function( $block_content, $block ) use ( $parsed_comment_author_name_block ) { + // Insert a Comment Author Name block (which requires `commentId` + // block context to work) after the Comment Content block. + if ( 'core/comment-content' !== $block['blockName'] ) { + return $block_content; + } + + $inserted_content = render_block( $parsed_comment_author_name_block ); + return $inserted_content . $block_content; + }; + + add_filter( 'render_block', $render_block_callback, 10, 3 ); + $parsed_blocks = parse_blocks( + '' + ); + $block = new WP_Block( + $parsed_blocks[0], + array( + 'postId' => self::$custom_post->ID, + ) + ); + $markup = $block->render(); + remove_filter( 'render_block', $render_block_callback ); + + $this->assertStringContainsString( + $comment_author_name_block_markup, + $markup, + "Rendered markup doesn't contain Comment Author Name block." + ); + } +}