I’m currently using the @auth0/auth0-react library to manage login and logout in my app, and it works great. However, I’m now looking to add automation tests to it and I’m looking for a way to fake logging in.
I did find a blog post at End-to-End Testing with Cypress and Auth0 which attempts to describe how to do this, but it doesn’t work with this library. Doing the login in the background, and then redirecting to the page as if it was an OAuth2 Implicit Grant simply does nothing. No errors, no network requests, and certainly not logged in.
It turns out that @auth0/auth0-react uses PKCE, which is great. But this means that I also can’t just fake a redirect to /?code=...&state=..., because the state value needs to be present in the a0.spajs.txs session storage object, and that also needs to store a valid code_verifier value.
Is there a recommended way to automation test logging in when using @auth0/auth0-react? Or should I rework with one of the other client libraries?
Cheers
Edit: I should say that right now I’m driving the Auth0 login dialog, and have had to configure it to force login every time - with prompt:"login". That’s not a great solution for a number of reasons, which is why I’m trying to find a better way to do this.
It looks like I can fake this from some other stuff I’ve found. In particular, if you set cacheLocation="localstorage" on the Auth0Provider then the resolved token details are stored in Local Storage instead of JavaScript memory. This means that if you’re able to generate values for the local storage key and value that are valid then you can inject these and presto you’re logged in.
Now, the values here are non-trivial. The key is easy enough: @@auth0spajs@@::[clientId]::[audience]::[scopes]. But the value is a JSON document containing:
Client ID
Token response details (Access Token, ID Token, Scopes, Expires In, Token Type)
Actual expiry time
Decoded ID Token details
It seems that if I can get all of these details and build a local storage with them correctly then I can set that, reload the page and auth0-react suddenly thinks I’m correctly logged in.
I’m hoping there’s something within auth0-spa-js that I can leverage to do this work for me, so that I can just give it the correct values and all is good. Watch this space
Not a lot of activity on this post so far, but I just wanted to say that I was able to adapt this to work for Cypress tests in an Angular app using the @auth0/auth0-angular SDK.
In case it helps others in this situation, some specifics:
When initializing the application, include cacheLocation: 'localstorage' in the config passed to AuthModule.forRoot()
Use password grant to fetch a valid token response from /oauth/token
Before each test, push JSON similar to the example above into localstorage using the key format mentioned by @sazzer: @@auth0spajs@@::[clientId]::[audience]::[scopes]
Voila, user is logged in for the purposes of the spec