首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取Firebase错误:在使用React jest库和jest时,没有创建任何Firebase应用程序‘[默认]’

获取Firebase错误:在使用React jest库和jest时,没有创建任何Firebase应用程序‘[默认]’
EN

Stack Overflow用户
提问于 2021-09-01 13:57:14
回答 1查看 454关注 0票数 1

我在React中使用Firebase auth,并尝试用react-hooks-testing-library测试它。我写的代码起作用了。但是,当我尝试用react-hooks-testing-library进行测试时,我得到了以下错误:

FirebaseError: Firebase:未创建Firebase应用程序“默认”,请调用Firebase App.initializeApp() ( App / No -app)。

以下是我的实际代码:

useAuth.tsx

代码语言:javascript
复制
const defaultValue = {
     .. some value here
}

const AuthContext = createContext(defaultValue)

const AuthContextProvider = (props) => {
    const auth = useFirebaseAuth()

    return (
        <AuthContext.Provider
            value={auth}
        >
            {props.children}
        </AuthContext.Provider>
    );
}

const useAuth = () => {
    return useContext(AuthContext)
}

// I will like to test the function and behaviour inside this hooks, useFirebaseAuth() here
export default function useFirebaseAuth() {

    const [user, setUser] = useState(null)

  
    const loginWithEmailPassword = (email: string, password: string) => {

        const auth = getAuth() // the error point to this line!!! 

        //this code I followed the Firebase docs    
        return signInWithEmailAndPassword(auth, email, password)
            .then(res => {

            }).catch(error => {

            })
    }

    const signUpWithEmailPassword = () => {

    }


    return {
        user,
        loginWithEmailPassword,
        signUpWithEmailPassword
    }

}

export { useAuth, AuthContextProvider }

在这个钩子里面将有三个项目,其中userloginWithEmailPasswordsignUpWithEmailPassword

这是我的测试

useAuth.test.tsx

代码语言:javascript
复制
import React from 'react'
import { renderHook, act } from '@testing-library/react-hooks/native'
import useFirebaseAuth from '../useAuth';

// Here I tried to mock the auth function of Firebase
jest.mock('firebase/app', () => {
    return {
        App: () => ({
            app: mockGetApp
        }),
        auth: () => ({
            signInWithEmailAndPassword: mockSignIn,
            createUserWithEmailAndPassword: mockSignUp
        })
    }
})

const mockInitializeFirebase = jest.fn()
const mockSignUp = jest.fn(() => Promise.resolve())
const mockSignIn = jest.fn(() => Promise.resolve())
const mockGetApp = jest.fn()

jest.mock('../../utils/initAuth', () => {
    return {
        app: mockInitializeFirebase
    }
})

describe('useAuth Hooks testing', () => {

    test('Login with Email and Password', () => {
        const { result } = renderHook(() => useFirebaseAuth())

        console.log(result)

        //arrange it, confirm the initial state 
        expect(result.current.user).toBe(null)
        expect(typeof result.current.loginWithEmailPassword).toBe('function')
        expect(typeof result.current.signUpWithEmailPassword).toBe('function')

        const email = 'abc@gmail.com'
        const password = '123456'
        // here act
        act(() => {
            // The problem come from this line
            result.current.loginWithEmailPassword(email, password)
        })
        // here assert 
        expect(mockSignIn).toBeCalledWith(email, password)

    })
})

因此,当我启动loginWithEmailPassword(email,password)函数时,它一直在显示No Firebase App error。但是在我的项目中,我已经有了这个文件,它已经初始化了Firebase应用程序。

./initFirebase.tsx,在这里已经初始化了应用程序,并在index.tsx中调用了它

代码语言:javascript
复制
import { initializeApp, getApps, getApp } from "firebase/app";
import getEnvVars from '../environment'

const env = getEnvVars()

interface firebaseType {
    apiKey: string,
    authDomain: string,
    projectId: string,
    messagingSenderId: string
}

let firebaseConfig: firebaseType;

if (env !== null) {

    const { apiKey, authDomain, projectId, messagingSenderId } = env
    firebaseConfig = {
        apiKey: apiKey,
        authDomain: authDomain,
        projectId: projectId,
        messagingSenderId: messagingSenderId
    };
}

export const initFirebase = () => {
    if (getApps().length === 0) {
        initializeApp(firebaseConfig);
    } else {
        getApp()
    }
}

因此,错误只发生在测试中,所以我认为我应该模拟initializeApp函数,并在测试的某个地方调用它。但我不知道该怎么做。

我刚开始在testing领域工作。有经验的人请帮忙。

以下是一个问题:

  1. 我的代码和测试发生了什么错误?

  1. ,我该怎么做才能解决这个错误?

提前谢谢你。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-01 16:50:24

通过这样的模拟来解决这个问题:

代码语言:javascript
复制
const mockSignUp = jest.fn(() => {
    return Promise.resolve({
        user: {
            uid: "fakeuid",
        },
    });
})
const mockSignIn = jest.fn(() => Promise.resolve({
    user: {
        uid: "fakeUid"
    }
}))

const mockGetAuth = jest.fn()

jest.mock('firebase/auth', () => {
    return {
        getAuth: () => mockGetAuth,
        signInWithEmailAndPassword: () => mockSignIn,
        createUserWithEmailAndPassword: () => mockSignUp
    }
})

注意到这一点:

getAuth: ()=> mockGetAuth中的3个函数,这将在firebase中模拟为getAuth()到我定义的mockGetAuth函数。

然后,在测试中,我可以像这样调用模拟函数:

代码语言:javascript
复制
// here check the mock function 
mockSignIn(mockGetAuth, email, password)
expect(mockSignIn).toBeCalledWith(mockGetAuth, email, password)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69015195

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档