18

我在 Laravel 5.4 框架上的项目,我正在使用Dusk进行浏览器测试。我有一个页面,其中有几个部分我想独立测试,但是我遇到了一个问题,我必须为每个单独的测试启动一个新的浏览器实例、登录并导航到该页面。

public function testExample()
{
  $this->browse(function (Browser $browser) {
    $browser->loginAs(1)
            ->visit('/admin/dashboard')
            ->assertABC()
            ->assertXYZ();
  });
}

因此,当我有 4-5 个这些时,我会为每个测试类class allTheThingsTest extends DuskTestCase生成4-5 个浏览器实例。显然,这很快就会失控,尤其是当我在部署前运行所有测试时。

就我而言,每个测试类一个浏览器实例是可以接受的,但我不知道如何做到这一点。所以这就是我要问的:

  • 是否可以在单个测试类中的测试函数之间记住/重用浏览器实例?
  • 如果是这样,怎么做?
4

1 回答 1

1

I feel like typically you would want a fresh browser instance for each test in your test class so that each test is starting out in a "fresh" state. Basically serving the same purpose as Laravel's DatabaseTransactions/RefreshDatabase testing traits.

However, if you do not want to login every time/every test method, you could try something similar to the following:

class ExampleTest extends DuskTestCase
{
    /**
     * An single instance of our browser.
     *
     * @var Browser|null
     */
    protected static ?Browser $browser = null;

    /**
     * Get our test class ready.
     *
     * @return void
     */
    protected function setUp(): void
    {
        parent::setUp();

        if (is_null(static::$browser)) {
            $this->browse(function (Browser $browser) {
                $browser->loginAs(1);
                static::$browser = $browser;
            });
        }
    }

    /** @test */
    public function first_logged_in_use_case()
    {
        static::$browser->visit('/admin/dashboard')->assertABC();
    }

    /** @test */
    public function second_logged_in_use_case()
    {
        static::$browser->visit('/admin/dashboard')->assertXYZ();
    }
}

I haven't tested this but essentially you're creating a static class property and assigning a logged in browser instance to it. Then you can use that same instance across all your test methods in your class.

于 2021-01-27T15:49:34.297 回答