brian_contrast's avatar

Testing Event::assertionDispatched Causes Error

I'm experiencing a strange issue when I try to test events being fired from my Model classes.

it('creates an invoice and dispatches the InvoiceUpdated event', function () {

    Event::fake([
        InvoiceUpdated::class,
    ]);

    $invoice = Invoice::factory()->create([
        'customer_id' => $this->customer->id,
        'company_id' => $this->user->company_id
    ]);

    Event::assertDispatched(InvoiceUpdated::class);
});

The test above fails with the following error:

Tests\Feature\Invoices\InvoiceTest > it creates an invoice and dispatches the InvoiceUpdated event                                    BadMethodCallException   
  Received Mockery_3_Illuminate_Auth_AuthManager::hasResolvedGuards(), but no expectations were specified

  at vendor\laravel\framework\src\Illuminate\Auth\AuthServiceProvider.php:103
     99▕     protected function registerEventRebindHandler()
    100▕     {
    101▕         $this->app->rebinding('events', function ($app, $dispatcher) {
    102▕             if (! $app->resolved('auth') ||
  ➜ 103▕                 $app['auth']->hasResolvedGuards() === false) {
    104▕                 return;
    105▕             }
    106▕
    107▕             if (method_exists($guard = $app['auth']->guard(), 'setDispatcher')) {

  1   vendor\laravel\framework\src\Illuminate\Auth\AuthServiceProvider.php:103
  2   vendor\laravel\framework\src\Illuminate\Container\Container.php:639

My test suite uses a beforeEach method to mock the Auth object and return a User model. The relevant section is below.

	$this->user = User::factory()->create();

    Auth::shouldReceive('guest')
        ->andReturn(false);
    Auth::shouldReceive('hasUser')
        ->andReturn(true);
    Auth::shouldReceive('id')
        ->andReturn($this->user->id);
    Auth::shouldReceive('user')
        ->andReturn($this->user);

If I remove the Event::fake call from my test the error disappears but then the test won't run with a different error:

Tests\Feature\Invoices\InvoiceTest > it creates an invoice and dispatches the InvoiceUpdated event                                    BadMethodCallException   
  Method Illuminate\Events\Dispatcher::assertDispatched does not exist.

  at vendor\laravel\framework\src\Illuminate\Macroable\Traits\Macroable.php:115
    111▕      */
    112▕     public function __call($method, $parameters)
    113▕     {
    114▕         if (! static::hasMacro($method)) {
  ➜ 115▕             throw new BadMethodCallException(sprintf(
    116▕                 'Method %s::%s does not exist.', static::class, $method
    117▕             ));
    118▕         }
    119▕

  1   vendor\laravel\framework\src\Illuminate\Macroable\Traits\Macroable.php:115
  2   vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:357
0 likes
0 replies

Please or to participate in this conversation.