【问题标题】:Simulating ajax request in CakePHP unit test在 CakePHP 单元测试中模拟 ajax 请求
【发布时间】:2014-08-28 17:05:12
【问题描述】:

我尝试了各种方法,包括按照本文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 请求。

【问题讨论】:

    标签: php ajax unit-testing cakephp


    【解决方案1】:

    您需要坚持使用 $this->request(在您的情况下为 $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

    【讨论】:

    • 我最终不得不在测试后“取消设置”全局变量 - 否则它会影响后续测试。所以我把 $_SERVER['HTTP_X_REQUESTED_WITH'] = '' 作为 ajax 测试的最后一行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多