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

后端 未结 6 1394
再見小時候
再見小時候 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 03:42

    At the time writing, I've examined these approaches

    • stubbing firebase network requests - really difficult. A bunch of firebase requests is sent continuously. There are so many request params & large payload and they're unreadable.
    • localStorage injection - as same as request stubbing. It requires an internally thorough understanding of both firebase SDK and data structure.
    • cypress-firebase plugin - it's not matured enough and lack of documentation. I skipped this option because it needs a service account (admin key). The project I'm working on is opensource and there are many contributors. It's hard to share the key without including it in the source control.

    Eventually, I implemented it on my own which is quite simple. Most importantly, it doesn't require any confidential firebase credentials. Basically, it's done by

    • initialize another firebase instance within Cypress
    • use that firebase instance to build a Cypress custom command to login

    const fbConfig = {
      apiKey: `your api key`, // AIzaSyDAxS_7M780mI3_tlwnAvpbaqRsQPlmp64
      authDomain: `your auth domain`, // onearmy-test-ci.firebaseapp.com
      projectId: `your project id`, // onearmy-test-ci
    
    }
    firebase.initializeApp(fbConfig)
    
    const attachCustomCommands = (
      Cypress,
      { auth, firestore }: typeof firebase,
    ) => {
      let currentUser: null | firebase.User = null
      auth().onAuthStateChanged(user => {
        currentUser = user
      })
    
      Cypress.Commands.add('login', (email, password) => {
        Cypress.log({
          displayName: 'login',
          consoleProps: () => {
            return { email, password }
          },
        })
        return auth().signInWithEmailAndPassword(email, password)
      })
    
      Cypress.Commands.add('logout', () => {
        const userInfo = currentUser ? currentUser.email : 'Not login yet - Skipped'
        Cypress.log({
          displayName: 'logout',
          consoleProps: () => {
            return { currentUser: userInfo }
          },
        })
        return auth().signOut()
      })
    
    }
    
    attachCustomCommands(Cypress, firebase)
    

    Here is the commit that has all integration code https://github.com/ONEARMY/community-platform/commit/b441699c856c6aeedb8b73464c05fce542e9ead1

提交回复
热议问题