簡體   English   中英

摩卡單元測試Firebase應用程序

[英]Mocha unit tests for Firebase app

我使用firebase 3.3.0並且我想在我的mocha單元測試中使用signInWithEmailAndPassword函數,但是我得到錯誤auth / network-request-failed

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

test.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"
  }

當你說“我想在我的摩卡單元測試中使用signInWithEmailAndPassword函數”時,我會告訴你,“為什么”?

您是否嘗試通過測試其身份驗證服務來幫助Firebase團隊? 這是很好的你,但如果你想測試你的應用程序,那么你應該被呼喚的單元測試,在所有火力點。 您真正想要檢查的是,類似於Firebase響應的響應由應用程序在響應返回后運行的代碼中正確處理。

如果我的任務是為此編寫測試,我會使用帶有mocha的sinon庫並創建一個調用不同函數的存根,該函數返回一些數據而不是實際調用Firebase:

這說明了一個sinon存根的語法:

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"
    }
});

可能你不再需要了,但是我沒有創建一個存根,而是使用了spyOn,它就像一個魅力。

在此輸入圖像描述

對於遇到此問題的任何其他人,我能夠確定來自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];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM