Is it possible to use Cypress e2e testing with a firebase auth project?

后端 未结 6 1398
再見小時候
再見小時候 2021-02-19 03:16

I am exploring Cypress for e2e testing, looks like great software. The problem is Authentication, the Cypress documentation explains why using the UI is very bad here.

So

6条回答
  •  温柔的废话
    2021-02-19 04:04

    This is becoming way easier with the upcoming Auth emulator. This has become easier with the Firebase Auth Emulator (firebase-tools >= 8.1.4).

    cypress/support/signAs.js:

    Cypress.Commands.add('signAs', (uid, opt) => {
      cy.visit('/')
    
      cy.window().its('firebase').then( fb => {
        cy.wrap( (async _ => {
          // Create a user based on the provided token (only '.uid' is used by Firebase)
          await fb.auth().signInWithCustomToken( JSON.stringify({ uid }) );
    
          // Set '.displayName', '.photoURL'; for email and password, other functions exist (not implemented)
          await fb.auth().currentUser.updateProfile(opt);
        })() )
      })
    })
    

    Use it as:

    cy.signAs('joe', { displayName: 'Joe D.', photoURL: 'http://some' });
    

    If you need to set .email or .password, there are similar functions for those, but this was sufficient for my tests. I can now impersonate any user ad-hoc, as part of the test. The approach does not need users to be created in the emulator; you can just claim to be one, with the particular uid. Works well for me.

    Note:

    Firebase authentication is in IndexedDB (as mentioned in other answers) and Cypress does not clear it, between the tests. There is discussion about this in cypress #1208.

提交回复
热议问题