I have a class that uses Laravel’s global event() function to fire off a single event when a model is changed. The only way I have been able to prevent this event from firing during unit tests is to actually namespace and declare a new event() function in the test itself and make it do nothing. It works, but it doesn’t seem like a pretty solution to me. I looked into the Laravel docs and I can see some people have used Event::fake() inside the test successfully, but when I try to do it I get:
BadMethodCallException: Method Mockery_0_Illuminate_Contracts_Events_Dispatcher::until() does not exist on this mock object
I’m on Laravel 5.4. Is there a cleaner way to prevent this event from firing during a test? I really dislike the idea of declaring an empty namespaced event() function.
EDIT:
The class I am testing is a UserDomain class. In one part of the logic it invokes Laravel’s global event() method:
event(new RoleChanged($this->user));
To suppress this from firing in a test I have tried Event::fake() and I have also tried using the trait WithoutEvents and its withoutEvents() method. Neither work, and the same error I mentioned above occurs both times.
Advertisement
Answer
I read some more docs on mocking in Laravel unit testing and I discovered that all I had to do is this at the beginning of the test:
$this->expectsEvents(RoleChanged::class);
This tells framework to acknowledge this event occurred but to not actually fire it off. Thanks everybody for your help. It led me to a workable solution.