測試依存項

有時候,測試需要某些先決條件或事件在執行前發生,否則測試不會成功。舉例來說,你可能只能驗證使用者能夠修改他們的帳戶,但你必須先驗證一個帳戶能夠被建立。

為了解決這個問題,Pest 提供了 depends() 方法,它允許「子系」測試指定它依賴於一個或多個「父系」測試。

1test('parent', function () {
2 expect(true)->toBeTrue();
3});
4 
5test('child', function () {
6 expect(false)->toBeFalse();
7})->depends('parent');

在這個範例中,child 測試在 parent 測試成功完成後才會被觸發。

如果 parent 測試失敗,child 測試將被略過,而且在你的測試結果中會顯示一則資訊訊息。

1test('parent', function () {
2 expect(true)->toBeFalse();
3});
4 
5test('child', function () {
6 expect(false)->toBeFalse();
7})->depends('parent');

上述範例會產生以下輸出

重要的是要記得,it() 函式預設會使用「it」為測試加上字首。因此,當透過 depends() 方法參照測試名稱時,你應該包含「it」字首。

1it('is the parent', function () {
2 expect(true)->toBeTrue();
3});
4 
5test('child', function () {
6 expect(false)->toBeFalse();
7})->depends('it is the parent');

結果輸出如下

父系測試甚至可以提供回傳值,這些回傳值可以當成 child 測試中的參數存取。

1test('parent', function () {
2 expect(true)->toBeTrue();
3 
4 return 'from parent';
5});
6 
7test('child', function ($parentValue) {
8 var_dump($parentValue); // from parent
9 
10 expect($parentValue)->toBe('from parent');
11})->depends('parent');

也可以為測試新增多重依存項。然而,所有父系測試都必須通過,而且每個測試回傳的值會以指定依存項相同的順序作為函式參數提供。

1test('a', function () {
2 expect(true)->toBeTrue();
3 
4 return 'a';
5});
6 
7test('b', function () {
8 expect(true)->toBeTrue();
9 
10 return 'b';
11});
12 
13test('c', function () {
14 expect(true)->toBeTrue();
15 
16 return 'c';
17});
18 
19test('d', function ($testA, $testC, $testB) {
20 var_dump($testA); // a
21 var_dump($testB); // b
22 var_dump($testC); // c
23})->depends('a', 'b', 'c');

儘管測試依存項並不常見,但它們可以優化你的測試並將重覆建立資源的需求減到最低。在下一章,我們將探討如何建立外掛程式:建立外掛程式