[英]Yii2 Functional test send ajax get request not working
我正在嘗試使用 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));
}
抓取響應方法是我自己在 \\Helper\\Functional.php 文件中編寫的方法:
public function grabResponse()
{
return $this->getModule('Yii2')->_getResponseContent();
}
當我轉儲響應時,我只看到站點/索引頁面中的 html。 除了站點默認值之外的任何路由都會發生這種情況。 如果我嘗試使用 site/index 做同樣的事情,那么它會返回:
string(36) "{"message":"hello world","code":100}"
我錯過了什么/做錯了什么?
注意Yii 路由和實際 URL 之間的區別。
sendAjaxGetRequest()的參數是 URL,而不是路由(至少如果您將其作為字符串傳遞,請參見下文)。
根據您的 UrlManager 配置,您可能有類似/index.php?r=site/about
URL,其中路由是site/about
。 你可以使用 Yii 的 Url helper 創建 URL:
$I->sendAjaxGetRequest(\yii\helpers\Url::to(['site/about']));
我不確定這一點,但如果你安裝了 Codeception Yii2 模塊,你也應該能夠像這樣通過路由:
$I->sendAjaxGetRequest(['site/about']);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.