huddledigital / zendesk-laravel

Laravel wrapper for zendesk/zendesk_api_client_php package.
MIT License
104 stars 70 forks source link

How To Mock Facade In Tests? #31

Open mikefromhl opened 10 months ago

mikefromhl commented 10 months ago

Is there a way to mock the Zendesk facade?

I'm following Laravel's documentation on Mocking Facades in Laravel 10, but I can't seem to get it working with the latest version of this package.

My ultimate goal is to ensure through testing that the methods to create or read tickets, users, etc. are being called in my controllers and models without making an external call to Zendesk to actually create the ticket, user, etc.

Here's a simple example:

// ZendeskController.php

use Huddle\Zendesk\Facades\Zendesk;

...

// The method that handles the route from the test below
public function getUser($id)
{
    return Zendesk::users()->find($id);
}
// ZendeskControllerTest.php

use Huddle\Zendesk\Facades\Zendesk;

...

/** @test */
public function the_zendesk_user_can_be_found()
{
    Zendesk::spy();

    // This user object has a valid zendesk_user_id property
    $this->actingAs($this->user)
        ->get("/api/zendesk/users/{$this->user->zendesk_user_id}");

    Zendesk::shouldHaveReceived('users')->once();
}

Running the test results in:

Method users(<Any Arguments>) from Mockery_0_Huddle_Zendesk_Services_ZendeskService should be called at least 1 times but called 0 times.

But, the test passes if I remove the Zendesk::spy() and Zendesk::shouldHaveReceived() lines, and returns the user if I dump the request.

What am I doing wrong?