How to reuse a Dusk test browser instance?

2019-04-25 07:45发布

问题:

My project on the Laravel 5.4 framework and I am using Dusk for browser tests. I have a page that has several sections I'd like to test independently, however I'm running into the problem where I have to start a new browser instance, login, and navigate to that page, for each individual test.

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

So when I have 4-5 of these in class allTheThingsTest extends DuskTestCase, I'm spawning 4-5 browser instances per test class. Obviously this gets out of hand quickly, especially when I'm running all of my tests pre-deployment.

One browser instance per test class is acceptable as far as I'm concerned, but I can't figure out how to make that happen. So here is what I'm asking:

  • Is it possible to remember/reuse a browser instance between test functions within a single test class?
  • If so, how?

回答1:

Quoting from laravel docs:

Sometimes, you may wish to bind something into the container that should only be resolved once, and the same instance should be returned on subsequent calls into the container:

$this->app->singleton('FooBar', function($app)
{
    return new FooBar($app['SomethingElse']);
});