【发布时间】:2012-03-13 02:26:36
【问题描述】:
是否可以在 symfony2 测试中模拟/发出 XMLHttpRequest 请求(ajax)?
【问题讨论】:
是否可以在 symfony2 测试中模拟/发出 XMLHttpRequest 请求(ajax)?
【问题讨论】:
搜索“有问题”的答案后,正确的语法是:
$crawler = $client->request('GET', '/foo/', array(), array(), array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
));
【讨论】:
Request#isXmlHttpRequest() 方法只是检查X-Requested-With 标头是否等同于XMLHttpRequest。如果这是您用来确定请求是否为 ajax 调用的方法,那么您可以通过在请求中添加适当的标头来模拟测试客户端中的行为:
class FooFunctionalTest extends WebTestCase
{
$client = static::CreateClient();
$crawler = $client->request('GET', '/foo/', array(), array(), array(
'X-Requested-With' => 'XMLHttpRequest',
));
// ...
}
更多信息可以在Request对象in the source code中找到。
【讨论】:
对于POST、PUT:
$crawler = $client->request('POST', '/foo/', array('param' => 'value'), array(),
array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
));
对于POST、PUT 和原始JSON 正文:
$crawler = $client->request('POST', '/foo/', array(), array(), array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
'CONTENT_TYPE' => 'application/json',
), '{"param": "value"}');
【讨论】:
如果您使用 Symfony 3.x 或 4.x,这是使用 POST 方法的正确方法。
$data = ['some' => 'value'];
$client = static::createClient();
$client->request('POST', '/some_uri', ['data' => $data], [],; [
'HTTP_X-Requested-With' => 'XMLHttpRequest',
]);
【讨论】: