lucatume / wp-snaphot-assertions
一组用于支持WordPress代码快照测试的实用工具。
Requires
- php: ^7.3|^7.4|^8.0
- ext-dom: *
- electrolinux/phpquery: ^0.9.6
- spatie/phpunit-snapshot-assertions: ^4.2
This package is auto-updated.
Last update: 2024-09-14 15:23:20 UTC
README
基于Spatie的PHPUnit快照断言包的WordPress代码快照测试,用于PHPUnit。
安装
composer require lucatume/wp-snaphot-assertions --dev
使用方法
在测试一些WordPress生成的和管理的代码的HTML输出时,快照测试非常有用。
在这种情况下,WordPress通常会生成时间相关的值,如非ces,以及完整的URL,如图片源。
这些环境和时间相关差异可能会因为错误的原因而破坏快照;例如,快照是在一台机器(比如说本地)上生成的,在另一台机器上运行(WordPress可能被托管在不同的URL上,测试肯定会在不同的时间运行,比如CI)。
为此,诞生了WPHtmlOutputDriver
驱动程序
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); } }
默认情况下,驱动程序将寻找具有id
、name
或class
(例如_wpnonce
)的默认列表中的时间相关字段;您可能希望使用WPHtmlOutputDriver::setTimeDependentKeys
方法添加或修改此列表。
同样,当驱动程序寻找用当前URL替换快照URL时,它将寻找一些属性;您可以使用WPHtmlOutputDriver::setUrlAttributes
方法修改这些属性。
WordPress的HTML通常包含包含帖子ID、标题和其他字段的属性和字符串;总的来说,快照的比较不应该失败,因为当快照生成时使用的随机帖子ID是23
,但在另一个测试运行中是89
。
要避免这种情况,请使用WPHtmlOutputDriver::setTolerableDifferences
方法定义在当前测试运行中不应触发失败的值(请参阅上面的示例);此外,可以使用运行相关变量来构建id
、class
、data
和其他属性:如果您知道渲染的HTML将包含如下内容(其中23
是帖子ID)
<div class="post-23" data-one="23-postfix" data-two="prefix-23"> <p>Foo</p> </div>
您可能希望告诉驱动程序,当前帖子ID是一个可容忍的差异,即使它以prefix-
或后缀-postfix
开头
$driver->setTolerableDifferences([$currentPostId]); $driver->setTolerableDifferencesPrefixes(['prefix-']); $driver->setTolerableDifferencesPostfixes(['-postfix']); $this->assertMatchesSnapshot($renderedHtml, $driver);
当HTML属性包含真正唯一或时间相关的值时,可以使用WPHtmlOutputDriver::setTimeDependentAttributes
方法完全排除这些属性。
// Void all the `data-one` attributes in the HTML document. $driver->setTimeDependentAttributes(['data-one']); // Void all the `.container data-two` and `.container data-three` attributes in the HTML document. $driver->setTimeDependentAttributes(['data-two', 'data-three'], '.container'); $this->assertMatchesSnapshot($renderedHtml, $driver);