use*_*694 2 php ajax unit-testing cakephp
我已经尝试了各种方法,包括按照这篇文章的建议为CakePHP控制器单元测试设置标题设置标题,但我似乎无法在我的控制器单元测试中同意ajax请求.
我有这种情况
if ($this->request->is('ajax')) {
Run Code Online (Sandbox Code Playgroud)
还有这个
if ($this->params['isAjax'] == 1) {
Run Code Online (Sandbox Code Playgroud)
但是条件不满意.我甚至尝试设置数组值$this->params['isAjax'] = 1;但是我得到了一个错误
Indirect modification of overloaded property RoomController::$params has no effect
Run Code Online (Sandbox Code Playgroud)
我的问题是如何在cakePHP中对控制器进行单元测试时如何成功模拟ajax请求.
您需要坚持$ this-> request($ this-> request-> params in your case).由于$ 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
}
Run Code Online (Sandbox Code Playgroud)
然后if ($this->request->is('ajax')) {}在你的代码中将工作得很好.
请参阅https://github.com/dereuromark/tools/wiki/Testing#testing-controllers