Simulating ajax request in CakePHP unit test

ajax, cakephp, php, unit-testing

Solution

You need to stick to $this->request ($this->request->params in your case). As $this->params itself is deprecated and should not be used anymore.

But in your case, all you need to do is to set the right $_SERVER or $_ENV key in your test case:

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
}

Then `if ($this->request->is('ajax')) {}` in your code will work just fine.

See https://github.com/dereuromark/tools/wiki/Testing#testing-controllers

Problem

I have tried various methods, including setting the headers as suggested by this post Setting headers for CakePHP Controller unit tests but I can't seem to simultae an ajax request in my controller unit test. I have this condition ``` if ($this->request->is('ajax')) { ``` and this ``` if ($this->params['isAjax'] == 1) { ``` but the conditions are not satisfied., I even tried setting the array value `$this->params['isAjax'] = 1;` but I got an error ``` Indirect modification of overloaded property RoomController::$params has no effect ``` My question is how can I successfully simulate an ajax request when unit testing a controller in cakePHP.

Original source