Search code examples
yii2codeception

Yii2 Functional test send ajax get request not working


I am trying to test an ajax request with a basic install of Yii2. I am just using the SiteController::actionAbout() method to try this out.

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

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

And in the test:

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

    die(var_dump($r));
}

The grab response method is one I wrote myself in a \Helper\Functional.php file:

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

When I dump out the response, I just see the html from the site/index page. This happens for any route except the site default. If I try to do the same thing using site/index then it returns:

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

What am I missing / doing wrong?


Solution

  • Note the difference between a Yii route and the actual URL.

    The argument to sendAjaxGetRequest() is the URL, not the route (at least if you pass it as a string, see below).

    Dependent on your UrlManager config you might have URLs like /index.php?r=site/about, where the route is site/about. You can use the Url helper of Yii to create the URL:

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

    I am not sure about this but if you have the Codeception Yii2 module installed you should also be able to pass the route like this:

    $I->sendAjaxGetRequest(['site/about']);