How we can test a ajax call using phpunit zend.
This is my ajax call in controller
public function indexAction()
{
if ( $this->getRequest()->isPost() )
{
if (self::isAjax()) {
$name = $this->getRequest()->getParam('name');
$email = $this->getRequest()->getParam('email');
$u = new admin_Model_User();
$u->email = $email;
$u->name = $name;
$u->save();
if(!empty($u->id)) $msg = "Record Successfully Added";
else $msg = "Records could not be added";
$this->results[] = array('status'=>true, 'msg'=>$msg);
echo $this->_helper->json($this->results);
} else {
echo "none-Ajax Request";
}
}else {
echo "Request not post";
}
}
private function isAjax() {
return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}
here is my test case
class AjaxjsonControllerTest extends ControllerTestCase
{
// testing not post area
public function testIndexAction() {
$this->dispatch('/ajaxjson');
$this->assertModule('admin');
$this->assertController('Ajaxjson');
$this->assertAction('index');
}
// testing not ajax request
public function testIndexNonajaxAction() {
$request = $this->getRequest();
$request->setMethod('POST');
$request->setPost(array(
'name' => 'name bar',
'email' => 'email x',
));
$this->dispatch('/ajaxjson');
$this->assertModule('admin');
$this->assertController('Ajaxjson');
$this->assertAction('index');
}
public function testPostAction() {
$request = $this->getRequest();
//$request->setHeader('X_REQUESTED_WITH','XMLHttpRequest');
$request->setHeader('HTTP_X_REQUESTED_WITH','XMLHttpRequest');
$request->setMethod('POST');
$request->setPost(array(
'name' => 'name bar',
'email' => 'email x',
));
$this->dispatch('/ajaxjson');
}
}
but this is not working. Has anyone an idea?