繁体   English   中英

使用JWT-Auth进行Laravel测试

[英]Laravel testing with JWT-Auth

我正在尝试测试由JWT_auth制成的api: https : //github.com/tymondesigns/jwt-auth

class UpdateTest extends TestCase
{
    use DatabaseTransactions;

    public $token;

    public function signIn($data = ['email'=>'mail@gmail.com', 'password'=>'secret'])
    {
        $this->post('api/login', $data);
        $content = json_decode($this->response->getContent());
        $this->assertObjectHasAttribute('token', $content);
        $this->token = $content->token;

        return $this;
    }

    /** @test */
    public function a_user_updates_his_account()
    {
        factory(User::class)->create([
            'name'              => 'Test',
            'last_name'         => 'Test',
            'email'             => 'mail@gmail.com',
            'mobile'            => '062348383',
            'function'          => 'ceo',
            'about'             => 'About me.....',
            'corporation_id'    => 1
        ]);

        $user = User::first();
        $user->active = 2;
        $user->save();

        $this->signIn();

        $url = '/api/user/' . $user->slug . '?token=' . $this->token;
        $result = $this->json('GET', $url);
        dd($result);
    }
}

结果总是:

The token could not be parsed from the request

我该如何工作!?

来源( https://github.com/tymondesigns/jwt-auth/issues/206

在这种情况下测试您的API的一种方法是绕过实际的令牌验证,但仍要登录您的用户(如果您需要识别用户)。 这是我们在最近的基于API的应用程序中使用的帮助程序方法的片段。

/**
 * Simulate call api
 *
 * @param  string $endpoint
 * @param  array  $params
 * @param  string $asUser
 *
 * @return mixed
 */
protected function callApi($endpoint, $params = [], $asUser = 'user@example.org')
{
    $endpoint = starts_with($endpoint, '/')
        ? $endpoint
        : '/' . $endpoint;

    $headers = [];

    if (!is_null($asUser)) {
        $token = auth()->guard('api')
            ->login(\Models\User::whereEmail($asUser)->first());

        $headers['Authorization'] = 'Bearer ' . $token;
    }

    return $this->json(
        'POST', 
        'http://api.dev/' . $endpoint,
        $params,
        $headers
    );
}

和这样使用:

$this->callApi('orders/list', [
        'type' => 'customers' 
    ])
    ->seeStatusOk()

基本上,目前还没有真正的方法。 在测试期间创建并传递给Laravel进行处理的虚假请求,以某种方式删除了令牌数据。

已经在一个问题中报告了该问题( https://github.com/tymondesigns/jwt-auth/issues/852 ),但是据我所知,目前还没有解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM