Running on Laravel 10, with PHPUnit 10.5.38, I have a middleware that adds the environment to the <title> tag so stakeholders are more aware of when they are on Dev or UAT environments.
<title>My Page</title> becomes <title>DEV - My Page</title>
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
$isHtmlResponse = $response->headers->get('Content-Type') === 'text/html; charset=UTF-8';
if (!app()->isProduction() && $isHtmlResponse) {
$content = $response->getContent();
$content = preg_replace(
'/<title>/i',
'<title>' . strtoupper(config('app.env')) . ' - ',
$content
);
$response->setContent($content);
}
return $response;
}
When I run unit tests with assertions against a view, the following error occurs:
The response is not a view.
Example test:
public function test_why_it_is_not_a_view(): void
{
$this
->get(route('my.login'))
->assertViewHas('x', 'y')
->assertOk();
}
This test should fail. There’s no x property with value y. The same happens on what should be passing tests.
When I exclude the middleware completely, things work. When I add logic to exclude the regex with app()->runningUnitTests(), things work.
So, what is it about $response->setContent($content) that causes upset?