Best way to unit test code that depends on http ca

2019-05-24 23:14发布

问题:

Lets say I have a log in and log out function that works with the firebase authentication system.

How would one unit test such a method? The firebase app instance gets imported and used in the log in function.

Code snippet if needed:

export function login(data) {
  return dispatch => {
    return firebaseAuth.signInWithEmailAndPassword(data.emailField, data.passField)
      .then(user => {
        dispatch({type: "SET_CURRENT_USER", payload: user})
        user.getToken().then(token => setAuthToken(token))
        localStorage.setItem("currentUser", JSON.stringify(user))
      })
  }
}

How can I mock something like this? Should I just set up a test email and password just for the purpose of testing the method? What would be a recommended way?

Thanks!

回答1:

With jest you can mock the function like this.

jest.mock('pathToFireBase', () => ({
   signInWithEmailAndPassword(email,password){
     if(password === 'correct') {
       return Promise.resolve({name: 'someUser'})
     } else {
       return Promise.reject({error: 'someError'})
     }
   }
}))

this will replace the signInWithEmailAndPassword in your firebaseAuth module with a function that either return a resolved or rejected promise depending on the password you pass to the function in your test.

Please have a look at the docs on how to handle promises in tests