Skip to content

Testing withSession() generates an error. #3190

Closed
@luispastendev

Description

@luispastendev

Hi! I am testing a method of my controller which displays a json only if an established session is found.

To perform the test I am using the following code since the path can be accessed only if the logged_in variable exists in session

public function testERP(){
        $values = [
            'logged_in' => TRUE,
            'username' => 'foo'
        ];

        $response = $this->withSession($values)->get('/');
        
        $response->assertSessionHas('logged_in',TRUE);
        print_r($response->getJSON());
        $response->assertStatus(200);
}

In my class it's like the following:

use CodeIgniter\API\ResponseTrait;
class Dash extends BaseController
{
    use ResponseTrait;
    public function index()
    {
        $session = \Config\Services::session();

        if($session->logged_in == TRUE){

            $data = [
                [
                    'id' => 1,
                    'username' => 'foo1',
                ],
                [
                    'id' => 2,
                    'username' => 'foo2',
                ],
            ];
            return $this->respond($data,200);
        }else{
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }
    }
}

imagen

The test only works correctly if I don't use the logged_in comparison but it is not correct because there must be a session to access the resource.

regards!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions