简体   繁体   中英

How to unit test if the cookie was queued or set in Laravel

I am working on a Laravel application. I am writing integration tests for my application. I am struggling to test Cookie logic. You can see my code below.

I am overriding the login method of LoginController adding the following bit

if (auth()->user()->hasRole(User::ROLE_ADMIN)) {
                $accessToken = GraphQL::login($request->get('email'), $request->get('password'));
                Cookie::queue("admin_access_token", $accessToken, (60 * 60 * 24) * 60);
            }

As you can see, what I am trying to do is that if the user is admin, it will log into another server and save the access token in a cookie. I am using Cookie::queue.

This is my test method.

/** @test */
    public function when_login_successful_access_token_is_generated_and_stored_in_cookie_if_user_is_restaurant_admin()
    {
        $this->post(route('login'), [
            'email' => $this->restaurantAdmin->email,
            'password' => 'password'
        ])->assertRedirect();

        dd(Cookie::get('admin_access_token'));//here, coolie value is always null
    }

When I run my test, as you can see in the comment, the cookie value is always null. What is wrong with my code and how can I fix it?

I would assume that the static Cookie::get() would try to fetch the cookie in the Request life cycle on the call. Since that is gone in the test, the cookie will always be null.

There is a method for seeing if a cookie exists on a response, you could use that and see if that gives the expected results.

$this->seeCookie('admin_access_token', 'yourtoken');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM