iT邦幫忙

2021 iThome 鐵人賽

DAY 26
0
Modern Web

當拉拉肉遇到單元測試,是否能夠擦出命運的火花?系列 第 27

[Day 26] 針對View來作測試

驗證view的資料

我們也可以針對view來做測試,
透過Laravel提供的測試方法,
我們可以不用透過http的方式,
直接傳參數給view來測試是否符合我們預期的結果

<?php

namespace Tests\Feature;

use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function test_a_welcome_view_can_be_rendered()
    {
        $view = $this->view('welcome', ['name' => '小魚']);

        $view->assertSee('小魚');
    }
}

除了assertSee之外,
Laravel還提供了其他常用的方法

方法 說明
assertSee 指定字串包含在回應當中
assertSeeInOrder 指定的字串陣列依序出現在回應當中
assertSeeText 指定字串包含在回應文字內容當中
assertSeeTextInOrder 指定的字串陣列依序出現在回應文字內容當中
assertDontSee 指定字串不包含在回應當中
assertDontSeeText 指定字串不包含在回應文字內容當中

另外我們也可以把view轉換成字串來做處理

$contents = (string) $this->view('welcome');

驗證錯誤訊息的模組

通常我們的表單當中可能會包含驗證模組,
我們可以來測試我們的模組

$view = $this->withViewErrors([
    'name' => ['Please provide a valid name.']
])->view('form');

$view->assertSee('Please provide a valid name.');

自己寫blade語法來做驗證

我們也可以自己寫blade語法,
然後傳參數進去驗證這個語法是否正確

$view = $this->blade(
    '<x-component :name="$name" />',
    ['name' => 'Taylor']
);

$view->assertSee('Taylor');

我們到目前為止整理了不少測試的方法,
想要知道更多方法的可以參考 Laravel官方文件
明天開始我們會開始來探討Laravel Dusk跟ChromeDriver的用法。


上一篇
[Day 25] 測試文件上傳
下一篇
[Day 27] 甚麼是ChromeDriver?可以自動駕駛嗎?
系列文
當拉拉肉遇到單元測試,是否能夠擦出命運的火花?31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言