Last active
February 4, 2023 21:45
-
-
Save nullthoughts/be1b823ac01ec0de599a4a4e6bf8cb69 to your computer and use it in GitHub Desktop.
Mock classes & routes in Laravel Dusk tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Providers; | |
class DuskServiceProvider extends ServiceProvider | |
{ | |
/** | |
* The classes that should be mocked for Dusk tests | |
* | |
* @var array | |
*/ | |
protected $classes = [ | |
AddressVerification::class => AddressVerificationMock::class, | |
]; | |
/** | |
* The additional routes that should be mocked for Dusk tests | |
* | |
* @var array | |
*/ | |
protected $routes = [ | |
'api/invoices/{invoice}' => [ | |
'method' => 'GET', | |
'action' => InvoiceControllerMock::class | |
], | |
]; | |
/** | |
* Register services. | |
* | |
* @return void | |
*/ | |
public function register() | |
{ | |
if (app()->environment('dusk')) { | |
$this->mockClasses(); | |
$this->mockRoutes(); | |
} | |
} | |
/** | |
* Mock classes | |
* | |
* @return void | |
*/ | |
protected function mockClasses() | |
{ | |
foreach ($this->classes as $class => $mock) { | |
$this->app->instance($class, new $mock); | |
} | |
} | |
/** | |
* Mock routes | |
* | |
* @return void | |
*/ | |
protected function mockRoutes() | |
{ | |
$router = app()->make('router'); | |
foreach ($this->routes as $route => $mock) { | |
$router->addRoute($mock['method'], $route, $mock['action']); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dusk is wonderful for testing, but lacks the ability to mock and swap classes like feature and unit tests.
The above service provider makes it possible to mock classes and routes when the environment is set to dusk (typically using .env.dusk.local). In this example, I'm mocking an external API service
/api/invoices
(utilized by Vue.js components) by overriding my environment variable for the API's endpoint:Note: the routes functionality will only append new routes, and cannot overwrite existing ones (I might explore that some more down the road, extending RouteCollection's add method)
.env
.env.dusk.local