duandi2853
2019-07-22 13:12 阅读 170
已采纳

如何使用中间件测试路由('auth:api')?

I'm writing some unit tests for a project I am working on and I can't seem to test posting as a logged in user.

I have tried adding a bearer token to the env file, this worked when on my machine, but fails with buddyworks running the tests after pushing.

 public function test_orders_route_authenticated_user () {

        $data =
            '{
                "orderID": "001241",
                "sku": "123456",
                "quantity": 9,
                "pricePerUnit": 78,
                "priceTotal": 702
            }';

        $this->user = factory(User::class)->create();;

        //dd($user);
        $response = $this->withHeaders([
            'Authorization'=>'MPBtsJN5qf',
            ])->json('POST', 'api/products',[
                $data
            ]);

        $response->assertStatus(200);

}

So this code gives me error 500. I have managed to get error 401 and 500, but never the intended status 200. Please help

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    douyuepi6485 douyuepi6485 2019-07-22 13:21

    As mentioned in the Passport documentation you can use Passport::actingAs(...):

    public function test_orders_route_authenticated_user()
    {
        Passport::actingAs(
            factory(User::class)->create()
        );
    
        $data = [
            'orderID'      => '001241',
            'sku'          => '123456',
            'quantity'     => 9,
            'pricePerUnit' => 78,
            'priceTotal'   => 702,
        ];
    
        $this->json('post', 'api/products', $data)->assertStatus(200);
    }
    
    点赞 评论 复制链接分享
  • dsgsgs30201 dsgsgs30201 2019-07-22 13:15

    You should apply jwt auth on your route like:

    Route::group(['middleware' => 'jwt.auth'], function () {
      Route::get('/index','IndexController@index');
    
    });
    
    点赞 评论 复制链接分享

相关推荐