Search code examples
laravel-sanctumvitest

How to Test laravel sanctum routes in vitest


I have a application using the Vue framework for the client, and laravel for the server.

My authentication is done via laravel sanctum, which is a cookie based authentication system. My current setup is running vitest in vs code. My client uses axios for api calls.

Unfortunately, I am unable to unit test the majority of my code due to authentication issues. (which is what I am hoping to resolve here)

I tried wrapping the applications login process in vitest, which I expected to behave the same as the browser.

My current attempt runs as:

  1. Execute applications login script with account credentials that only exists on the test server.
  2. I can see that the server responds with Set-Cookie header.
  3. Vitest doesn't see the cookie attached to the document, nor axios.
  4. Manually setting the authentication cookie results in an error due to session mismatch.

Server side testing runs fine; however, the goal here is to test client side code. Since the login form works on the browser, I'd expect it to work in Vitest as well.

It's as if either vitest or vs code doesn't maintain the state for me to use consistently.

Thus, I searched and couldn't find any topics on it.

Since I'm mostly looking for process, I haven't posted my code, but can post it later if that'll be an easier path forward.


Solution

  • Working solution was:

    1. Setting the origin on the client when making requests.
    2. Enabling said origin with CORS
    3. Modifying the SESSION_DOMAIN environment variable on Laravel to match said origin.

    That being said, now I use passport, and have a client for testing