6

I'm using Cypress for e2e tests on my Firebase web app, and I want test runs to always start fresh from an non-authenticated state.

How do I prevent Firebase Auth sessions from persisting across e2e test runs?

Currently, I have a logout() function call at the end of the tests. But if a test fails before that point, logout() often doesn't get called, and I have to manually log out before the next test run.

Brian A Bird
  • 378
  • 2
  • 18
  • I don't know anything about firebase, but if it is storing the auth session as a cookie you could call `cy.clearCookie("nameOfCookie")` in your `beforeEach()` – Brendan Aug 10 '18 at 20:44
  • Unfortunately, that doesn't work. All cookies and local storage is dumped automatically by Cypress at the beginning of every test run anyway. Firebase must use other mechanisms to persist state. – Brian A Bird Aug 10 '18 at 20:49
  • It is supposed to blow away the cookies between tests, but I have found that to not be reliable and have had to add that call in my tests to reset the session. Good luck! – Brendan Aug 10 '18 at 21:20
  • If `logout()` is working for you, call it in `afterEach()`, see [this document](https://docs.cypress.io/guides/references/best-practices.html#Using-after-or-afterEach-hooks). – Richard Matsen Aug 11 '18 at 00:18
  • @RichardMatsen The document you linked to specifically says that devs _shouldn't_ clean up in `afterEach()` and then it lists the reasons why. Hence, I'm trying to find the correct way to implement. – Brian A Bird Aug 11 '18 at 01:18
  • The 'dangling state' paragraph is talking about moving from test to test with previous state, which seems like good practice. But you are saying that you specifically want to logout each test - so logout between tests. – Richard Matsen Aug 11 '18 at 02:13
  • Nowhere do I indicate a desire to logout between _each_ test. "Test run" refers to a single run-through of _all_ tests. – Brian A Bird Aug 11 '18 at 13:46
  • Were you able to mock creating users with cypress? – Gabriel May 02 '20 at 02:23

1 Answers1

23

Hi as mentioned you should clear firebase auth token in your beforeEach() method.

However depending on the version of firebase the auth token might be stored in different storage. Localstorage and indexdDB should be cleared.

indexedDB.deleteDatabase('firebaseLocalStorageDb');
rsjaffe
  • 5,600
  • 7
  • 27
  • 39
Supralex
  • 281
  • 2
  • 3
  • 1
    The question can be read a couple of ways, but it seems from clarification in comments that the token should be cleared in a `before()` not in `beforeEach()`. –  Aug 11 '18 at 21:25
  • There's a more generic solution to clearing the indexedDb [here](https://github.com/cypress-io/cypress/issues/1208#issuecomment-727628571): It cleans all listed dbs. – pico_prob Mar 15 '22 at 19:47