How to do POST request in Codeception FunctionalTest with JSON Body

Viewed 1472

Im using Codeception with Yii2. I need to do a POST request with json content body. I dont want to use REST module cause have not even been able config it yet. (Thats a longer story...)

I have been able to write my GET tests fantastic. Now with the first POST test, Im stuck.

  1. There is a $I->amOnPage([]) method in Functional Test which can only do GET request.
  2. sendAjaxPost does not allow sending content body with POST.
  3. $I->sendPOST('api/xyz',"{\"xyz\":1}") also did not work cause Yii did not get any route so instead loaded the homepage. The path got lost in the call stacks.
  4. There is a InnerBrowser->_loadPage method which allows me to do a request with all configurable way but I cannot find a way to access it.

Any way to get access to InnerBrowser object from the test? I have tried $I->getModule('PhpBrowser')->_loadPage or $this->getModule('Yii2')

2 Answers

You can use I->SendAjaxPostRequest which has an array argument with the POST values to send with the request.

You can update backend code to accept both raw inputs and params, so you can pass array in Codeception test and raw input in api

    $data = json_decode(file_get_contents("php://input"));

    if(!$data) {
        $data = (object) Yii::$app->request->post ();
        $detail = (object) $data->detail;
    } else {
        $detail = $data->detail;
    }
Related