Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

How to test an observer is wired up

If it isn't, then no other logic tests matter

Joel Clermont
Joel Clermont
2024-07-05

From our daily Laravel tips email. Get the next one in your inbox.

We don't use observers a lot in our applications, but there are some use cases where they make sense

And I'm a big believer in writing tests to gain confidence in our code. Most test logic is on making sure the listener does what it's supposed to do, but if the observer isn't even wired up, none of those tests will catch it.

I like to write a simple test in my listener test suite to validate that my listener is actually wired up to the model events I expect:

public function testWiredUpSuccessfully(): void
{
    Event::fake();

    Event::assertListening(
        sprintf("eloquent.created: %s", Client::class),
        sprintf('%s@created', ClientObserver::class)
    );
}

It's quick to write, clear to read, and will catch if you fail to wire up the observer correctly.

Here to help,

Joel

P.S. You are writing tests for your Laravel app, right? If not, let's talk.

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.