Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sstringer's avatar

How do I set a userAgent header string to a phpunit test in Laravel 5.3?

I'm writing a unit test for my support contact form. Before the app sends the email to me, it pulls the user's browser information from their userAgent string.

Is it possible to fake the user-agent string before calling Laravel's InteractsWithPages' "visit" method?

To be clear, I'm not looking to set the user-agent string as a form value. Rather, I need to set the user-agent in the test's request header.

Has anyone solved this in their own unit testing?

0 likes
6 replies
willvincent's avatar

I've not done it, but try calling this method before you call visit().

    /**
     * Define a set of server variables to be sent with the requests.
     *
     * @param  array  $server
     * @return $this
     */
    protected function withServerVariables(array $server)
    {
        $this->serverVariables = $server;
        return $this;
    }

Pass in an array like this:

[
  'HTTP_USER_AGENT' => 'User agent string here'
]

or if you want to set it as the header key, user-agent, instead of the server variable key, you'd do something like this:

$headers = [
  'user-agent' => 'user agent value here'
];

$this->withServerVariables($this->transformHeadersToServerVars($headers));
// then visit and do whatever else.
1 like
bretto36's avatar

$this->post($url, $data, [ 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3', ];

I use this. I know it's an old question but might help someone eventually

1 like

Please or to participate in this conversation.