在 WordPress 项目的开发和维护过程中,对生成的 HTML 代码进行测试至关重要。然而,由于 WordPress 的动态特性,生成的 HTML 经常包含一些时间敏感或者环境依赖的值,例如 nonce、URL 等。这些值在不同的运行环境中可能不同,导致传统的快照测试经常失败,即使代码逻辑本身没有问题。为了解决这个问题,lucatume/wp-snapshot-assertions 提供了一套专门针对 WordPress 的快照测试工具。
lucatume/wp-snapshot-assertions 基于 Spatie 的 phpunit-snapshot-assertions 包,专门为 WordPress 环境定制,它提供了一个 WPHtmlOutputDriver,可以帮助我们忽略 HTML 中那些时间敏感或者环境依赖的差异,从而使得快照测试更加稳定可靠。
安装
使用 Composer 安装非常简单:
<code class="bash">composer require lucatume/wp-snaphot-assertions --dev</code>
使用方法
以下是一个使用 WPHtmlOutputDriver 的例子:
<code class="php">use Spatie\Snapshots\MatchesSnapshots;
use tad\WP\Snapshots\WPHtmlOutputDriver;
class MySnapshotTest extends \Codeception\TestCase\WPTestCase {
use MatchesSnapshots;
/**
* Test snapshot for render
*/
public function test_snapshot_render() {
// from some environment variable
$currentWpUrl = getenv('WP_URL');
$snapshotUrl = 'http://wp.localhost';
$driver = new WPHtmlOutputDriver($currentWpUrl, $snapshotUrl);
$sut = new MyPluginHTMLRenderingClass();
// create a random post and return its post ID
$postId= $this->factory->post->create();
$renderedHtml = $sut->renderHtmlFor($postId);
$driver->setTolerableDifferences([$postId]);
$driver->setTolerableDifferencesPrefixes(['post_', 'post-']);
$driver->setTolerableDifferencesPostfixes(['-single', '-another-postfix']);
$this->assertMatchesSnapshot($renderedHtml, $driver);
}
}</code>在这个例子中,我们首先创建了一个 WPHtmlOutputDriver 实例,并指定了当前 WordPress 的 URL 和快照 URL。然后,我们创建了一个随机的 post,并使用 MyPluginHTMLRenderingClass 渲染了 HTML。
为了忽略 post ID 带来的差异,我们使用了 setTolerableDifferences 方法,将 post ID 添加到可容忍的差异列表中。此外,我们还使用了 setTolerableDifferencesPrefixes 和 setTolerableDifferencesPostfixes 方法,指定了 post ID 的前缀和后缀,以便忽略更多由 post ID 引起的差异。
主要功能
WPHtmlOutputDriver 会查找一些时间敏感的字段,例如 _wpnonce,并忽略它们带来的差异。你可以使用 setTimeDependentKeys 方法自定义这些字段。WPHtmlOutputDriver 会自动将快照 URL 替换为当前 WordPress 的 URL。你可以使用 setUrlAttributes 方法自定义需要替换的属性。setTolerableDifferences 方法可以指定哪些值不应该触发快照测试失败。setTolerableDifferencesPrefixes 和 setTolerableDifferencesPostfixes 方法可以指定可容忍差异的前缀和后缀。setTimeDependentAttributes 方法可以完全排除某些属性的比较。优势
lucatume/wp-snapshot-assertions 可以提高 WordPress 代码的快照测试的稳定性。WPHtmlOutputDriver 提供了许多方便的方法,可以简化快照测试的代码。lucatume/wp-snapshot-assertions 可以轻松地集成到现有的 WordPress 项目中。实际应用
lucatume/wp-snapshot-assertions 非常适合以下场景:
通过使用 lucatume/wp-snapshot-assertions,我们可以更加自信地进行 WordPress 代码的修改和重构,因为我们可以通过快照测试来确保代码的输出没有发生意外的变化。
以上就是使用lucatume/wp-snapshot-assertions如何解决WordPress代码的快照测试问题的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号