Search code examples
laraveltestinggloballaravel-7

Laravel 7: unit test set default request header in setUp()


I want to set my headers for all requests in a test in the setUp method instead of doing it to all the tests separately.

Is there an easy way to do this?

So par example:

$this->withHeaders([
            'Authorization' => 'Bearer ' . $response['data']['token'],
            'Accept' => 'application/json'
        ])

To:

setUp(){
$this->setHeaders([
            'Authorization' => 'Bearer ' . $response['data']['token'],
            'Accept' => 'application/json'
        ]);
}

Solution

  • Of course. You could create an intermediary parent class TestCaseWithToken (or whatever you'd like to name it) that is going to extend the PHPUnit\Framework\TestCase and add your overriden method there

    protected function setUp(): void 
    {
       parent::setUp();
       // set your headers here
       $this->withHeaders([
                'Authorization' => 'Bearer ' . $this->getBearerToken(),
                'Accept' => 'application/json'
            ]);
    
    }
    
    protected function getBearerToken()
    {
       return '';
    }
    

    Additionally if your token changes in the $response variable, you could build a function that returns the token so you could easily override the method in the individual test classes. You could opt for a class property and a setter method, will work the same.

    If you want to get the token of the user you want to log in, it can be easily done. Just make the getBearerToken method return something like auth('api')->login($this->authUser);(this is goint to return the actual token) and set the $authUser once per test file. Hope this helps you in the right direction.