Index: tests/phpunit/testcases/activity/functions.php
===================================================================
--- tests/phpunit/testcases/activity/functions.php
+++ tests/phpunit/testcases/activity/functions.php
@@ -4,6 +4,8 @@
  */
 class BP_Tests_Activity_Functions extends BP_UnitTestCase {
 
+	protected static $ping = false;
+
 	/**
 	 * @ticket BP4488
 	 */
@@ -1947,4 +1949,68 @@
 		$this->assertEqualSets( [ $a1 ], bp_activity_get_user_favorites( $u1 ) );
 		$this->assertSame( $latest_update, bp_get_user_meta( $u1, 'bp_latest_update', true ) );
 	}
+
+	/**
+	 * @ticket BP8340
+	 */
+	public function test_oembed() {
+		$u1 = self::factory()->user->create();
+		$a1 = self::factory()->activity->create(
+			array(
+				'user_id'   => $u1,
+				'component' => 'activity',
+				'type'      => 'activity_update',
+				'content'   => 'Test
+
+https://www.youtube.com/watch?v=8Are9dDbW24
+
+Ha',
+			)
+		);
+
+		// Helper to instantiate activity loop and check activity for oEmbed.
+		$loop = function( $id ) {
+			bp_has_activities( [ 'in' => $id ] );
+			bp_the_activity();
+
+			// Assert that YouTube link was converted to iframe.
+			add_filter( 'oembed_result', array( $this, 'check_oembed_ping' ) );
+			$this->assertContains( '<iframe', bp_get_activity_content_body() );
+
+			// Uncomment to check loading="lazy" attribute addition
+			//$this->assertContains( '<iframe loading="lazy"', bp_get_activity_content_body() );
+
+			remove_filter( 'oembed_result', array( $this, 'check_oembed_ping' ) );
+		};
+
+		// Instantiate activity loop for the first time.
+		$loop( $a1 );
+
+		// Check that oEmbed was used.
+		$this->assertTrue( self::$ping );
+
+		// Now, check that oEmbed was cached in activity meta.
+		$meta  = bp_activity_get_meta( $a1 );
+		$cache = current( current( $meta ) );
+		$this->assertContains( '<iframe', $cache );
+		$this->assertTrue( 0 === strpos( key( $meta ), '_oembed_' ) );
+
+		// Lastly, instantiate activity loop for a second time.
+		self::$ping = false;
+		$loop( $a1 );
+
+		// oEmbed shouldn't have fired this time around.
+		$this->assertFalse( self::$ping );
+
+		// Clean up after ourselves!
+		$GLOBALS['activities_template'] = null;
+	}
+
+	/**
+	 * Helper method to determine if we used oEmbed to ping a provider.
+	 */
+	public function check_oembed_ping( $retval ) {
+		self::$ping = true;
+		return $retval;
+	}
 }
