Laravel:PHPUnit 并与 JavaScript 交互

Laravel: PHPUnit and interacting with JavaScript

我的 Laravel 应用程序中有一个由 JavaScript 驱动的非常简单的弹出对话框。本质上,在单击时,class 被添加到弹出窗口 div,它使用 CSS 过渡将其不透明度从 0 更改为 1。

这是我的测试:

public function testCantFindCodePopup()
{
  $customer = $this->createCustomer();
  $this->fillOutEmailAndDob($customer);

  $this->visit('/product-codes/new')
       ->dontSee("Still can't find your code?");
  $this->click('Can\'t find your code?');
         sleep(0.5);
  $this->see("Call customer service");
}

转换需要 300 毫秒,所以我认为 sleep500 毫秒可以解决问题,但没有骰子。

实际上,dontSee("Still can't find your code?") 部分的测试失败了,即使该文本位于弹出窗口内,加载时设置了 display: none

我是不是做错了什么,或者 PHPUnit 不知道 CSS 和 JavaScript 就像 capybara 一样(因为它在无头浏览器中运行)。

如果我不能将 PHPUnit 用于这种类型的集成测试,是否有类似的东西我可以可以使用?请注意,我在 PHPUnit 中还有大约 70 个其他测试,因此无论有什么其他工具,都不能完全替代;理想情况下,它会与我的 PHPUnit 测试一起存在。

编辑

blade 模板的相关部分:

<div class="form-control">
          <label for="product-code">Enter Your{{$second}}Code</label>
          <input type="text" id="product-code" name="product-code" />
        </div>
        <button class="btn btn-dark" type="submit">Submit</button>
        <span class="label-explanation js__popup-toggle">Can't find your code?
          <div class='popup'>
            <span class="popup__close">&times;</span>
            <img src="/assets/images/find-code-pop-up.png" alt="[alt text]" />
            <p class="popup__cannot-find">Still can't find your code?<br/> Call customer service at xxx-xxx-xxxx.</p>

相关CSS:

.popup
  width 300px
  position absolute
  left 35%
  bottom 0
  transition width 0.3s, height 0.3s, opacity 0.3s, transform 0.45s
  opacity 0
  background rgba(255,255,255,0.9)
  color $brand-primary-dark
  text-align center
  transform scale(0)
  p
    font-size 16px
    text-transform none
    line-height 1.15
  &.js__display
    height auto
    opacity 1
    transform scale(1)
    z-index 9999

.popup__close
  font-size 20px
  position absolute
  top 0
  right 5px
  transition font-size 0.3s
  &:hover
    font-size 24px

你没有做错任何事。在这种情况下,PHPUnit 不知道 CSS 和 JavaScript。我正在检查 Laravel 测试模块源代码(它扩展了 PHPUnit 功能)并且它只使用了一个爬虫。因此,它没有 运行 任何客户端脚本。实际上,它甚至不呈现页面。

我还没用过,你可以试试phpunit-spiderling

我看到这是一个非常古老的问题,但只是为了记录:

如果您想测试浏览器功能,可以查看 Laravel Dusk:

https://laravel.com/docs/5.8/dusk

例如,

Dusk 使用 Chrome 驱动程序访问本地计算机上的项目。因此,如果您使用 Vue.js 之类的框架,它也会执行 javascript 。

这是测试的样子:

public function test_careers_page_shows_vacancies()
{
    $this->browse(function (Browser $browser) {
        $career = \App\Career::first();
        $browser->visit("/careers")
                ->assertSee("Join our team!")
                ->pause(1000) // Pause for a second
                ->waitForText("Careers loaded") // Or wait for text
                ->assertSee($career->title);
    });
}

请注意,Dusk 将使用您的 local 环境,而 phpunit 可能会使用 testing 环境。例如,我为 phpunit 使用 sqlite 环境。但是 Dusk 浏览到使用不同数据库的“http://myproject.test/”。您可以通过在本地计算机上设置测试数据库来解决此问题。