Skip to content

Instantly share code, notes, and snippets.

@nullthoughts
Last active February 4, 2023 21:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nullthoughts/be1b823ac01ec0de599a4a4e6bf8cb69 to your computer and use it in GitHub Desktop.
Save nullthoughts/be1b823ac01ec0de599a4a4e6bf8cb69 to your computer and use it in GitHub Desktop.
Mock classes & routes in Laravel Dusk tests
<?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']);
}
}
}
@nullthoughts
Copy link
Author

nullthoughts commented Feb 4, 2023

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

APP_ENV=production
EXTERNAL_ENDPOINT="https://api.stripe-ish.com"

.env.dusk.local

APP_ENV=dusk
EXTERNAL_ENDPOINT=""

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment