如何检查Laravel刀片组件是否已加载?

时间:2020-09-28 04:02:46

标签: phpunit laravel-blade laravel-7

我正在提供一个将提供blade components的包装。因此,此软件包的用户可以将刀片模板上的组件用作:

<x-mypackage-component-a/>

这些组件位于我的软件包的src/Components文件夹下。如here所述,使用loadViewComponentsAs()方法将这些组件加载到包服务提供程序中:

$this->loadViewComponentsAs('mypackage', [
    Components\ComponentA::class,
    ...
]);

现在,我需要对phpunit进行一些测试,以检查组件是否由包服务提供商加载,如下所示:

public function testComponentsAreLoaded()
{
    $this->assertTrue(/*code that check 'x-mypackage-component-a' exists*/);
}

是否有任何方法(使用Laravel框架)来检查刀片组件名称是否存在和/或已加载?

对于包含以下代码的软件包提供的一组刀片视图,我已经设法进行了类似的操作:

// Views are loaded on the package service provider as:

$this->loadViewsFrom($viewsPath, 'mypackage');

// The phpunit test method is:

public function testViewsAreLoaded()
{
    $this->assertTrue(View::exists('mypackage::view-a'));
    $this->assertTrue(View::exists('mypackage::view-b'));
    ...
}

谢谢!

2 个答案:

答案 0 :(得分:0)

没有方法或帮助程序来检查组件是否存在,但是从那时起刀片组件在laravel中是类,因此您可以检查特定组件类是否存在:

// application namespaces

namespace App\View\Components;

use Illuminate\View\Component;

// define component
class mypackage extends Component { ... }


// check component
public function testViewsAreLoaded(){
    $this->assertTrue(class_exists('\Illuminate\View\Component\mypackage'));
    ...
}

答案 1 :(得分:0)

最后设法找到一种解决方法,我将解释这一点,因为它可能对其他读者有用。首先,您需要加载component classes使用的视图集(通常在render()方法上使用的视图)。在我的特殊情况下,组件视图位于resources/components文件夹中,因此我不得不在包服务提供者的boot()方法上插入下一个代码:

// Load the blade views used by the components.

$viewsPath = $this->packagePath('resources/components');
$this->loadViewsFrom($viewsPath, 'mypackage');

packagePath()是一种方法,用于将标准路径(从软件包根文件夹)返回到接收到的参数。

接下来,再次使用boot()方法,我必须按照问题中的说明加载组件:

$this->loadViewComponentsAs('mypackage', [
    Components\ComponentA::class,
    Components\ComponentB::class,
    ...
]);

最后,为了进行测试以断言视图,并且组件由服务提供商正确加载,我创建了下一个要与phpunit一起使用的方法:

public function testComponentsAreLoaded()
{
    // Check that the blade component views are loaded.

    $this->assertTrue(View::exists('mypackage::component-a'));
    $this->assertTrue(View::exists('mypackage::component-b'));
    ...

    // Now, check that the class components aliases are registered.

    $aliases = Blade::getClassComponentAliases();

    $this->assertTrue(isset($aliases['mypackage-component-a']));
    $this->assertTrue(isset($aliases['mypackage-component-b']));
    ...
}

作为附加信息,我必须说我的phpunit测试类是从Orchestral/testbench TestCase类继承的,您可能需要包括View和{{1 }}测试文件上的外观。我还使用下一种方法来确保程序包的服务提供者的Blade方法在运行测试之前在测试环境中执行:

boot()