2016-08-21 89 views
13

我用火力3.3.0,我想用signInWithEmailAndPassword功能在我的摩卡單元測試,但我得到的錯誤認證/網絡請求失敗摩卡單元測試火力地堡應用

Unhandled rejection Error: A network error (such as timeout, interrupted connection or unreachable host) has occurred. 

測試.js文件

const FIREBASE_CONFIG = { 
    apiKey: "AIzaSyDdA1POUWy9eid1AdBYuMdxch_k8ob7Qrg", 
    authDomain: "my-app.firebaseapp.com", 
    databaseURL: "https://my-app.firebaseio.com", 
    storageBucket: "my-app.appspot.com", 
}; 

const FIREBASE_API_REF = firebase.initializeApp(FIREBASE_CONFIG); 

before(function (done) { 

     promise = new Promise(function (resolve, reject) { 
      return FIREBASE_API_REF.auth().signInWithEmailAndPassword(firstUserEmail, firstUserPassword) 
      .then(function (userData) { 
       firstUserId = userData.uid; 
       resolve(userData); 
       done(); 
      }, function (error) { 
       return reject(error); 
      }) 
     }); 

    }); 

的package.json

"scripts": { 
    "test": "mocha --grep ./e2e.js --invert --compilers js:babel-register -R spec --ui bdd --timeout 7000" 
    } 
+0

您將需要顯示「FIREBASE_API_REF」引用的內容。此外,代碼還存在其他問題:'done'永遠不會被調用;決不會被稱爲;你不需要創建自己的承諾 - 這是一個[反模式](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#the-deferred-anti-pattern)。 – cartant

+0

@cartant感謝您的回覆,這不是'before'函數的完整部分。我只是想顯示一段代碼,我不能調用'signInWithEmailAndPassword'函數。請看我編輯的問題。 – Matt

+0

我認爲這個問題的部分問題是不清楚你在問什麼,並且你已經剪掉了部分測試代碼 - 「describe」和「it」調用在哪裏?另外,您還沒有指定如何運行測試:在使用Karma的瀏覽器中;或者在Node中使用mocha命令? – cartant

回答

1

當你說:「我想用signInWithEmailAndPassword功能在我的摩卡單元測試」那麼我會告訴你,「爲什麼」?

您是否試圖通過測試其驗證服務是否有效來幫助Firebase團隊?這很好,但如果你想測試你的應用程序,那麼你應該在單元測試中調用firebase。您真正想要檢查的是,響應返回時運行的代碼中的響應類似於Firebase響應的響應,由您的應用程序正確處理。

如果我寫一個測試爲了這個,我會使用興農庫摩卡和創建一個調用不同的函數返回一些數據的存根,而不是實際調用到火力地堡任務:

這說明語法的興農存根:

var stub = sinon.stub(object, "method", func); 

這是我會在你的例子做:

var stub = sinon.stub(FIREBASE_API_REF.auth(), "signInWithEmailAndPassword" 
, () => { 

    // Simply return a JSON object that is similar to the normal response from Firebase 
    return { 
    name: "Jim", 
    data: { 
     something: "some stuff" 
    } 
}); 
+0

嘿吉姆 - 我在考慮如何使用數據庫的摩卡測試來測試Firebase安全規則。爲此登錄用戶將非常有用。 –

+0

嗯,你可以做一些像集成測試一樣的驗證安全規則,而不依賴於你的前端UI。在您的「快樂案例」測試中,使用虛擬用戶帳戶登錄,嘗試訪問數據庫對象,並斷言您可以獲取對象。然後,您可以進行另一項測試,作爲無權訪問的虛擬用戶登錄。對他來說,你可以斷言對DB對象的請求被拒絕(它返回null或請求失敗等)。祝你好運! :) – Jim

1

可能你已經不再使用它了,但不是創建一個存根,而是使用spyOn,它的功能就像一個魅力。

enter image description here

1

對於任何人面對這個問題,我能夠確定從jsdom全球XMLHttpRequest對象問題就來了。我可以通過使用此代碼來設置我的全局變量來擺脫錯誤:

var doc = jsdom.jsdom('<!doctype html><html><body></body></html>'); 
global.window = doc.defaultView; 

for (var key in window) { 
    if (!window.hasOwnProperty(key)) continue; 
    if (key in global) continue; 
    if (key == 'XMLHttpRequest') continue; 

    global[key] = window[key]; 
}