Symfony как протестировать AJAX-запрос
В моем проекте у меня есть часть моей формы, которая отправляет запрос AJAX:
$.ajax({
url: '/bio_control/sample',
type: 'POST',
dataType: 'json',
data: {sample_number: $(input_field).val()},
});
, который активирует следующий метод контроллера:
/**
* @Route("/bio_control/sample", name="get_bio_control_sample")
*/
public function getBioControlSampleAction(Request $request)
{
$sample_number = $request->request->get('sample_number');
/**
* Additional logic not shown for brevity.
*/
$user_id = $user->getId();
$response = array("code" => 100, "success" => true, "sample_number" => $sample_number, "sample_data" => $sample[0], "new_user" => false, "user_id" => $user_id);
return new JsonResponse($response);
}
Я хотел бы иметь возможность протестировать этот запрос изолированно, но я не уверен, как написать объект запроса.
Пока что моя первая попытка:
public function testGetBioControlSample()
{
$helper = $this->helper;
$client = $this->makeClient();
$crawler = $client->request('POST', "/bio_control/sample", array(), array('sample_number' => 67655), array(
'CONTENT_TYPE' => 'application/json',
'HTTP_X-Requested-With' => 'XMLHttpRequest'
));
$this->assertStatusCode(200, $client);
}
Не удается, потому что, похоже, он отправляет форму (я получаю ошибку, связанную с тем, что поле формы, совершенно не связанное с пустым запросом AJAX, является пустым).
Может ли кто-нибудь продемонстрируйте, как правильно написать такой тест?
2 answers
Требуется ли для этого URL-адреса аутентификация?
Мне нравится использовать LiipFunctionalTestBundle для моих функциональных тестов, и они обычно выглядят так:
<?php
declare(strict_types=1);
namespace Tests\Your\Namespace;
use Liip\FunctionalTestBundle\Test\WebTestCase;
class PostResourceActionTest extends WebTestCase
{
public function testShouldReturnResponseWithOkStatusCode(): void
{
$credentials = [
'username' => 'user',
'password' => 'pass'
];
$client = $this->makeClient($credentials);
$payload = ['foo' => 'bar'];
$client->request(
'POST',
'/the/url/',
$payload,
[],
['HTTP_Content-Type' => 'application/json']
);
$this->assertStatusCode(200, $client);
}
}
Возможно, ошибка, которую вы получаете, заключается в том, что форма входа запрашивает аутентификацию?
Точный синтаксис, который я использовал для решения этой проблемы, был следующим:
public function testGetBioControlSample()
{
$helper = $this->helper;
$client = $this->makeClient();
$crawler = $client->request(
'POST',
"/bio_control/sample",
array('sample_number' => 67655),
array(),
array('HTTP_Content-Type' => 'application/json')
);
$JSON_response = json_decode($client->getResponse()->getContent(), true);
$this->assertStatusCode(200, $client);
$this->assertNotEmpty($JSON_response);
$this->assertEquals($JSON_response["code"], 100);
$this->assertEquals($JSON_response["success"], true);
$this->assertEquals($JSON_response["sample_number"], 67655);
}
Я считаю, что мне не нужно было: 'HTTP_X-Requested-With' => 'XMLHttpRequest'
в последнем аргументе массива.
Кроме того, я привел array('sample_number' => 67655)
неверный аргумент.