Yii2功能测试发送AJAX的GET请求不工作

问题描述 投票:2回答:1

我想测试一个基本的安装Yii2的Ajax请求。我只是用SiteController :: actionAbout()方法来尝试了这一点。

public function actionAbout()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    return [
        'message' => 'hello world',
        'code' => 100,
    ];
}

而在测试:

public function sendAjax(\FunctionalTester $I)
{
    $I->sendAjaxGetRequest('site/about');
    $r = $I->grabResponse();

    die(var_dump($r));
}

抓斗响应法是一个我写我自己的\辅助\ Functional.php文件:

public function grabResponse()
{
    return $this->getModule('Yii2')->_getResponseContent();
}

当我dump出来回应,我刚才看到从网站/索引页的HTML。出现这种情况,除了该网站默认的路由。如果我尝试使用网站/索引后返回给做同样的事情:

string(36) "{"message":"hello world","code":100}"

我缺少/做错了吗?

yii2 codeception
1个回答
1
投票

注意一个Yii route和实际URL之间的差异。

sendAjaxGetRequest()的参数是URL,而不是路线(至少如果你把它作为一个字符串,见下文)。

依赖于你UrlManager的配置,你可能有像/index.php?r=site/about,在此路由是site/about网址。您可以使用Yii中的URL辅助函数来建立的网址:

$I->sendAjaxGetRequest(\yii\helpers\Url::to(['site/about']));

我不知道这个,但如果你已经安装了Codeception Yii2模块,你也应该能够通过这样的路径:

$I->sendAjaxGetRequest(['site/about']);
© www.soinside.com 2019 - 2024. All rights reserved.