Can't use Auth emulator – `onAuthStateChanged` never fires in the app on init
filingroove opened this issue · 6 comments
Describe the bug
I do everything as described in README.md for using emulators, but Auth in particular seems to be initialized twice, which leads to app not working.
To Reproduce
- Do as docs suggest for using an emulator
app/firebase.js for the app itself
import firebase from 'firebase'
import 'firebase/auth';
...
firebase.initializeApp(fbConfig)
....
// plain string for simplicity
firebase.auth().useEmulator('http://localhost:9099')
cypress/support/firebase.ts - almost the same thing in terms of auth
import firebase from 'firebase'
import 'firebase/auth';
import { attachCustomCommands } from 'cypress-firebase'
...
firebase.initializeApp(fbConfig)
....
// plain string for simplicity
firebase.auth().useEmulator('http://localhost:9099')
...
attachCustomCommands({ Cypress, cy, firebase })
cypress/support/index.js
import './commands'
import './firebase'
Expected behavior/code
I expect the app and original Auth instance there to work
Additional Context/Screenshots
Hey, thanks for reporting! For clarity what about the app doesn't work at that point? Does auth not point to the emulators? Does Firebase or the App just not work at all?
Wondering if us only calling the initialize at the cypress level if the app hasn't already been initialized may help, but if so we would want to document that. Something like
// Only initialize firebase if it hasn't already been initialized
if (firebase.apps?.length === 0) {
firebase.initializeApp(fbConfig)
firebase.auth().useEmulator('http://localhost:9099')
}
Hey :) Thanks for reply.
So the issue for me was invalid/lacking FIREBASE_AUTH_EMULATOR_HOST
env variable. I was too quick to open this issue so I'm closing it now 😅
Okay, so that worked for a while and then stopped working completely. But I got what's wrong :)
My app relies on onAuthStateChanged
to start initializing. onAuthStateChanged
is called once when firebase.auth()
is initialized with null
as an argument. So, when I use cypress-firebase
, despite firebase app instances being different and in different scopes, onAuthStateChanged
fires in Cypress and then never fires in the app.
Have same issue. Any solution?
@filingroove I am interested in knowing how you dealt with onAuthStateChanged only firing in cypress.
I just got this working after running in circles. (Note: I am NOT using cypress-firebase at this time, I have a manual implementation. However, I think this point is still relevant.)
I only got this to work by using browserLocalPersistence on both the Cypress end and the application end! Notice that it is local persistence, NOT session persistence. (You might not see that if you're just scanning your code quickly.)
I was comfortable proving it worked by having a single test running that logs the user in. Then, refreshing the test runner and seeing it log in again. Hope that helps someone.