【问题标题】:laravel unit test Invalid JSON was returned from the routelaravel 单元测试 从路由返回了无效的 JSON
【发布时间】:2017-09-05 13:35:47
【问题描述】:

我为 laravel 的登录编写了这个单元测试

class LoginTest extends TestCase
{

/** @test */
    public function auth()
    {
       $this->withoutMiddleware();
    $this->visit('/login')
        ->post('/login', ['example@example.com', "password"=>"1234"])
        ->seeJson([
            "login"=>"true"
        ]);
    $this->get('/dashboard');

}

}

但我得到了这个错误

Invalid JSON was returned from the route. Perhaps an exception was thrown?

我该如何解决这个问题?

【问题讨论】:

    标签: json laravel unit-testing laravel-5 login


    【解决方案1】:

    我建议您使用 Guzzle Library 并向您的路由发出请求,然后转储完整响应:

            $response = $http->request('POST', 'http://your_laravel_public/login', [
                'form_params'=>[
                    'username' => 'example@example.com',
                    'password' => '1234'
                ]
            ]);
            $response_array = json_decode((string) $response->getBody(), true);//use this to see the actual response
            dd($response_array);
    

    这很有用,因为您稍后可能会在项目中使用 Passport 或任何其他身份验证服务。那时您将需要发送标头以进行授权,而您不能通过本机 laravel 单元测试来做到这一点。

    试一试。

    【讨论】:

    • 我尝试了第二个,但我得到了这个错误:调用未定义的方法 LoginTest::getBody()
    • 那么请按照我的回答中提到的获取 guzzle 库
    猜你喜欢
    • 1970-01-01
    • 2016-03-13
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多