jivanrij's avatar

How to test an event that is triggered by a request done with something different then $this->get()

I'm trying to find the best way to test if an event is triggered when a specific endpoint of my API is requested. Normally I'm testing events like this:

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

SomeClass::doSomethingThatTriggersTheEvent();

Event::assertDispatched(function (MyEvent $event) {
    return $event->my_value == 'something-to-check';
});

But when I can't trigger the logic directly and need to do it through the API call it doesn't work.

I'm trying to find the best way to test if an event is triggered when a specific endpoint of my API is requested.

I'm trying something like this:

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

Http::get('http://localhost/my-path');

Event::assertDispatched(function (MyEvent $event) {
    return $event->my_value == 'something-to-check';
});

I guess, that is fails, has something to do with the fact that the process that triggers the get call is a different process than the one of the test.

Currently I'm thinking of creating an instance of the controller and calling it the hard way, something like this:

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

MyPathController::show(new Request);

Event::assertDispatched(function (MyEvent $event) {
    return $event->my_value == 'something-to-check';
});

I doubt this would be the best solution.

I hope someone has a better solution here, thanks!

0 likes
5 replies
jivanrij's avatar

That works, but that's because (I guess) the $this->get() uses Illuminate\Foundation\Testing\Concerns\MakesHttpRequests::createTestResponse() and does not really do a request. I'm working with a package that posts AS2 messages and used GuzzleHttp\Client to do that.

(I'll update the title to better fit this problem)

MohamedTammam's avatar

@jivanrij What do you want to test here? the trigger being fired or testing what the event does.

If you want to test whether the event is fired or not, you can do as I mentioned earlier. If you want to test that the event is working you need to test it according to what it does. For example, if your event adds records to the DB, then you need to assert that there's a new record. And that type of testing doesn't related to the event itself.

jivanrij's avatar

@MohamedTammam The flow I want to test is as follows: Within the controller the code catches an EDI message that was posted to this route. For this, I'm using a package that uses the GuzzleHttp client. After the code from the package has interpreted the message and I can read it, I'm able to dispatch the correct event.

In my test, I'm posting an EDI message to that endpoint and want to check if the event is dispatched.

Please or to participate in this conversation.