使用Firebase Auth模拟器以编程方式创建用户 [英] Create a user programatically using Firebase Auth emulator

查看:119
本文介绍了使用Firebase Auth模拟器以编程方式创建用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Firebase Auth模拟器编写开玩笑的测试,并继续收到以下CORS错误.

I am trying to write jest tests using the Firebase Auth emulator and continue to receive the following CORS error.

console.error
    Error: Headers X-Client-Version forbidden
        at dispatchError (/Users/me/my-project/node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:62:19)
        at validCORSPreflightHeaders (/Users/me/my-project/node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:99:5)
        at Request.<anonymous> (/Users/me/my-project/node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:367:12)
        at Request.emit (events.js:315:20)
        at Request.onRequestResponse (/Users/me/my-project/node_modules/request/request.js:1059:10)
        at ClientRequest.emit (events.js:315:20)
        at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:641:27)
        at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17)
        at Socket.socketOnData (_http_client.js:509:22)
        at Socket.emit (events.js:315:20) undefined

测试非常简单:

import { renderHook, act } from "@testing-library/react-hooks"
import faker from "faker"
import { useAuth, FirebaseProvider, firebase } from "./index"


const wrapper = ({ firebase, children }) => {
  return <FirebaseProvider firebase={firebase}>{children}</FirebaseProvider>
}

const createUser = ({ email = faker.internet.email(), password = faker.internet.password({ length: 6 }) } = {}) => {
  return firebase
    .auth()
    .createUserWithEmailAndPassword(email, password)
    .then(user => user)
}

const signUserIn = ({ email, password } = {}) => {
  return firebase
    .auth()
    .signInWithEmailAndPassword(email, password)
    .then(user => user)
}

describe("useAuth", () => {
  it("will return the user", async () => {
    const { result } = renderHook(() => useAuth(), { wrapper, initialProps: { firebase } })
    const email = faker.internet.email()
    const password = faker.internet.password()
    await act(async () => {
      const user = await createUser({ email, password }) // this fails
      await signUserIn({ email, password }) //and so does this
    })
    expect(result.user).toEqual({ email, password })
  })
})

索引文件供参考:

const FirebaseProvider = ({ children, firebase }) => {
  const firestore = firebase.firestore()
  const auth = firebase.auth()

  if (useEmulator()) {
    firestore.useEmulator("localhost", 8080)
    auth.useEmulator("http://localhost:9099/")
  }

  const value = { firestore, auth }

  return <FirebaseContext.Provider value={value}>{children}</FirebaseContext.Provider>
}

const throwError = hook => {
  throw new Error(`${hook} must be used within a FirebaseProvider`)
}

const useAuth = () => {
  const context = useContext(FirebaseContext)
  if (context === undefined) throwError("useAuth")

  const [user, setUser] = useState()

  useEffect(() => {
    const cleanup = context.auth.onAuthStateChanged(authUser => {
      authUser ? setUser(authUser) : setUser(null)
    })
    return () => cleanup()
  })

  return { ...context.auth, user }
}

我尝试使用实际仿真器使用的REST端点(如下),并且它以相同的方式出错.

I have tried using the REST endpoint that the actual emulator uses (below) and it errors in the same way.

http://localhost:9099/identitytoolkit.googleapis.com/v1/projects/<my-project>/accounts

在使用玩笑时,是否有要让它运行的方法?还是在运行测试时需要使用仿真器UI创建帐户,将其导出并重新导入?

Is there anyway to get this to run when using jest? Or do I need to create the accounts using the emulator UI, export them and re-import when I am running tests?

我发现我可以使用下面的REST端点使用户成为测试中的用户,但是它绕过了模拟器并成为了真实用户.

I have found I can use the REST endpoint below to make a user in the test, however it bypasses the emulator and makes a real user.

https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=<api-key>

推荐答案

jsdom引发该错误,因为它不支持通配符用于access-control-allow-header,但是firebase使用通配符(请参阅此 jsdom的问题和此 https://github.com/jsdom/jsdom /pull/3073 https://github.com/jsdom/jsdom/pull /2867 .

The error is thrown by jsdom because it doesn't support wildcard for access-control-allow-headers, but firebase uses the wildcard (see this issue for jsdom and this pull request related to firebase). There are two open pull requests to fix this issue: https://github.com/jsdom/jsdom/pull/3073 and https://github.com/jsdom/jsdom/pull/2867.

可以通过手动更改node_modules文件夹中的相关代码或通过使用fork作为package.json中的依赖项来解决此问题:

The issue can be fixed by either changing the relevant code manually in the node_modules folder or by using the fork as dependency in the package.json:

"jsdom": "silviot/jsdom#fix/allow-headers"

如果jsdom不是直接依赖项,则可以在顶层的package.json中添加以下内容:

If jsdom isn't a direct dependency, then you can add the following to the package.json at the top level:

"resolutions": {
  "jsdom": "silviot/jsdom#fix/allow-headers"
}

如果使用了分叉,则jsdom文件夹中会缺少一些自动生成的文件.这些可以通过在文件夹中运行npm installyarn install来生成.要自动执行此操作,可以将prepare脚本添加到package.json:

If the fork is used there are some auto-generated files missing in the jsdom folder. These can be generated by running npm install or yarn install in the folder. To automate this you can add a prepare script to the package.json:

"scripts": {
  "prepare": "cd node_modules/jsdom && yarn"
},

这篇关于使用Firebase Auth模拟器以编程方式创建用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆