I’m currently trying to write PHP tests using pest for a search feature within a chat component. The component works fine when being used in my test environment though i’m unable to get a certain test to pass. The objective is to be able to return multiple messages that meet a specific search term.
Here is the test itself in ChatSearchTest.php:
/** @test */
public function the_component_can_return_multiple_search_results()
{
$messages_fixed_content = ChatMessage::factory(2)
->for($this->members[0], 'from')
->for($this->members[1], 'to')
->create([
'content' => 'test123'
]);
$messages_random_content = ChatMessage::factory(1)
->for($this->members[0], 'from')
->for($this->members[1], 'to')
->create();
$messages = $messages_fixed_content->merge($messages_random_content);
$chat_search = 'test123';
$component = Livewire::test(ChatSearch::class, ['partnership' => $this->partnership])
->set('chat_search', $chat_search)
->call('getSearchResults', $chat_search);
->assertCount('messages', 2);
}
And the relevant code it’s testing in ChatSearch.php:
public function updatedChatSearch()
{
$this->getSearchResults();
}
public function getSearchResults()
{
$search_results = $this->getMessagesQuery()->get();
$this->messages = $search_results;
$this->have_results = true;
}
protected function getMessagesQuery()
{
$query = $this->partnership
->chatMessages()
->with('from')
->with('shareable');
if ($this->chat_search) {
$query->search('content', $this->chat_search);
}
$query->latest();
return $query;
}
public function goToMessage($message_id)
{
$this->emitUp('goToSearchResult', $message_id);
}
The issue is that $this->messages returns an empty collection during the test, whereas on the actual testing environment, it works. If I dump out at the end of getSearchResults() it correctly shows $this->have_results as true though $this->messages returns an empty collection, as does $search_results.