Skip to content

Commit

Permalink
Feature | Reuse Global Mock Client With Saloon::fake()
Browse files Browse the repository at this point in the history
  • Loading branch information
Sammyjo20 committed Feb 7, 2024
1 parent ea38f6f commit 39bfa1b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Saloon.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,19 @@ class Saloon
*/
public static function fake(array $responses): MockClient
{
return MockClient::global($responses);
$mockClient = static::mockClient();

$mockClient->addResponses($responses);

return $mockClient;
}

/**
* Retrieve the global mock client
*/
public static function mockClient(): MockClient
{
return MockClient::global();
return MockClient::getGlobal() ?? MockClient::global();
}

/**
Expand Down
20 changes: 20 additions & 0 deletions tests/Feature/MockRequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

declare(strict_types=1);

use Saloon\Http\Faking\MockClient;
use Saloon\Http\PendingRequest;
use Saloon\Laravel\Facades\Saloon;
use Saloon\Http\Faking\MockResponse;
Expand Down Expand Up @@ -231,3 +232,22 @@ function (PendingRequest $request): MockResponse {
expect($responseA->json())->toEqual(['request' => 'https://tests.saloon.dev/api/user']);
expect($responseA->status())->toEqual(200);
});

test('the same global mock client is reused on further calls', function () {
$mockClientA = Saloon::fake([
new MockResponse(['name' => 'Sam'], 200),
]);

$mockClientB = Saloon::fake([
new MockResponse(['name' => 'Alex'], 200),
]);

expect(MockClient::getGlobal())->toEqual(new MockClient([
new MockResponse(['name' => 'Sam'], 200),
new MockResponse(['name' => 'Alex'], 200),
]));

expect($mockClientA)->toBe($mockClientB);
expect($mockClientA)->toBe(Saloon::mockClient());
expect($mockClientB)->toBe(Saloon::mockClient());
});

0 comments on commit 39bfa1b

Please sign in to comment.