Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock tymondesigns/jwt-auth in Laravel 5?

I just added tymondesigns/jwt-auth to support token auth, and consequently my test cases are failing because there is no token on the headers parameters. How can I mock (using Mockery) a component to bypass this?

Note: $this->be() doesn't work

like image 900
Christopher Francisco Avatar asked May 05 '15 18:05

Christopher Francisco


1 Answers

An alternative is to authenticate the request during test execution passing a particular user. This is how did it:

# tests/TestCase.php

/**
 * Return request headers needed to interact with the API.
 *
 * @return Array array of headers.
 */
protected function headers($user = null)
{
    $headers = ['Accept' => 'application/json'];

    if (!is_null($user)) {
        $token = JWTAuth::fromUser($user);
        JWTAuth::setToken($token);
        $headers['Authorization'] = 'Bearer '.$token;
    }

    return $headers;
}

Then in my tests I use it like this:

# tests/StuffTest.php

/**
 * Test: GET /api/stuff.
 */
public function testIndex()
{
    $url = '/api/stuff';

    // Test unauthenticated access.
    $this->get($url, $this->headers())
         ->assertResponseStatus(400);

    // Test authenticated access.
    $this->get($url, $this->headers(User::first()))
         ->seeJson()
         ->assertResponseOk();
}

Hope this help you all. Happy coding!

like image 121
Rubens Mariuzzo Avatar answered Sep 19 '22 00:09

Rubens Mariuzzo