Search code examples
javascriptunit-testingfirebasevue.jsvue-test-utils

How should I test vue components when using Firebase?


I'm writing unit tests for a vue project that uses firebase. The tests are using vue-test-utils.

The thing is I'm having trouble trying to bypass the auth, and with every test I find myself doing something like this.

...
const login = async () => {
return firebase.auth().signInWithEmailAndPassword(email, pass).then(
    res => {
        return res
    },
    err => {
        return new Error(err)
    })
}
...
describe('some component', () => {
    it('test something', async () => {
        try {
            await login()
            ...
        } catch (e) {
            ...
        }
    })
    it('test something else', async () => {
        try {
            await login()
            ...
        } catch (e) {
            ...
        }
    })
})

My question is. What is the recommended way to test vue components that use firebase and how to avoid having to login for every test?

Hope I explained my question correctly!

I ended up doing this, as in my case it's enough to do it once.

...
beforeAll(() => {
  return login()
})

describe('some component', ...

Solution

  • One approach is to use a beforeEach function in your test suite to get authenticated/check if authentication is still valid, simply:

    beforeEach(() => {
        try {
            await login()
            ...
        } catch (e) {
            ...
        }
    })
    

    However, are you doing this logic directly in a vue component? You ideally don't want to make these kind of calls directly from your vue components. If you move that logic out of your component and into a service class (or go a step further and use vuex to manage your state etc..), then you can test the firebase logic separately from your component logic.