首页 > 解决方案 > 使用 jest 和模拟器调用登录的 Firebase Auth 测试抛出错误:禁止标头 X-Client-Version

问题描述

我尝试使用 firebase js sdk localy 登录一个虚拟用户。我正在运行默认的 firebase 模拟器。调用该函数后,我得到以下异常:

    Error: Headers X-Client-Version forbidden
        at dispatchError (C:\Users\user\Documents\Projekte\Backend\functions\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:62:19)
        at validCORSPreflightHeaders (C:\Users\user\Documents\Projekte\Backend\functions\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:99:5)
        at Request.<anonymous> (C:\Users\user\Documents\Projekte\Backend\functions\node_modules\jsdom\lib\jsdom\living\xhr\xhr-utils.js:367:12)
        at Request.emit (events.js:315:20)
        at Request.onRequestResponse (C:\Users\user\Documents\Projekte\Backend\functions\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

      at VirtualConsole.<anonymous> (node_modules/jsdom/lib/jsdom/virtual-console.js:29:45)
      at dispatchError (node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:65:53)
      at validCORSPreflightHeaders (node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:99:5)
      at Request.<anonymous> (node_modules/jsdom/lib/jsdom/living/xhr/xhr-utils.js:367:12)
      at Request.onRequestResponse (node_modules/request/request.js:1059:10)

  console.log
    t {
      code: 'auth/network-request-failed',
      message: 'A network error (such as timeout, interrupted connection or unreachable host) has occurred.',
      a: null
    }

      at Object.<anonymous> (test/test.ts:275:12)

如果我尝试连接到我的在线项目,它工作正常,但我想用模拟器本地执行我的测试。

示例代码:


const app = firebase.initializeApp(firebaseConfig);

app.auth().useEmulator("http://localhost:9099");
app.firestore().settings({
    host: "localhost:8080",
    ssl: false,
});

test('Example test case', async () => {
        try {
            const cred: UserCredential = await app.auth().signInWithEmailAndPassword("foo@bar.de", "bla2377");
            expect(cred).toBeTruthy();
            expect(cred.user).toBeTruthy();
        } catch (e) {
            console.log(e);
            expect(true).toBeFalsy();
        }
    });

环境信息:

标签: node.jsfirebasefirebase-authentication

解决方案


jsdom 不支持 firebase 使用的通配符 access-control-allow-headers。这个答案修复了异常。


推荐阅读