[英]write unit test request->ajax() laravel
how to write test for this function ?? 如何为此功能编写测试? how to test request-ajax()??
如何测试request-ajax()?
public function getChangeLoc(Request $request, $loc)
{
if ($request->ajax()) {
if(!in_array($loc, config('loc.available'))) {
return response()->json([
'status' => 'ERROR',
'message' => 'Not available'
]);
}
Session::put('locale', $loc);
return response()->json([
'status' => 'OK',
'loc' => $loc,
]);
}
if(!in_array($loc, config('loc.available'))) {
return Redirect::to('/?unknown-loc);
}
Session::put('loc', $loc);
if(filter_var($request->input('redirect_url', ''), FILTER_VALIDATE_URL)) {
return Redirect::to($request->input('redirect_url'));
}
return Redirect::to('/');
}
I test the function like this 我测试这样的功能
$this->visit('/loc/en')
->seePageIs('/admin/client')
but its not see request->ajax? 但它看不到request-> ajax吗?
To test ajax requests you can implement function in your TestCase class this method. 要测试ajax请求,可以在TestCase类中使用此方法实现功能。 Your request needs HTTP_X-Requested-With header.
您的请求需要HTTP_X-Requested-With标头。
protected function ajaxPost($route = '', array $parameters = [])
{
return empty($route) ? null : $this->json(
'post',
$route,
$parameters,
['HTTP_X-Requested-With' => 'XMLHttpRequest']
);
}
Now you can test your classes 现在您可以测试您的课程
$this->ajaxPost(route('your.route'), ['foo' => 'bar'])->seeJson([
'is_ok' => true,
]);
Remember: it's not unit tests. 请记住:这不是单元测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.