我尝试了各种方法,包括按照此帖Setting headers for CakePHP Controller unit tests的建议设置标题,但我似乎无法在控制器单元测试中同意ajax请求。
我有这个条件
if ($this->request->is('ajax')) {
和这个
if ($this->params['isAjax'] == 1) {
但条件不满意。我甚至尝试设置数组值$this->params['isAjax'] = 1;
但我收到错误
Indirect modification of overloaded property RoomController::$params has no effect
我的问题是如何在cakePHP中对控制器进行单元测试时如何成功模拟ajax请求。
答案 0 :(得分:9)
您需要坚持使用$ this->请求($ this-> request-> params)。 因为$ this-> params本身已被弃用,不应再使用了。
但在您的情况下,您需要做的就是在测试用例中设置正确的$ _SERVER或$ _ENV键:
testSomeAjaxAction() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$url = Router::url(array('controller' => 'posts', 'action' => 'update', 'ext' => 'json', '?' => array('value' => 2)));
$options = array(
'return' => 'vars'
);
$result = $this->testAction($url, $options);
// Assert
}
然后代码中的if ($this->request->is('ajax')) {}
就可以了。
请参阅https://github.com/dereuromark/tools/wiki/Testing#testing-controllers