Reputation: 8942
I use firebase 3.3.0 and I want to use signInWithEmailAndPassword function in my mocha unit test, but I get error 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"
}
Upvotes: 13
Views: 3250
Reputation: 974
For anybody else facing this problem, I was able to determine the problem came from the global XMLHttpRequest
object from jsdom. I was able to get rid of the error by using this code for setting my global variables:
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];
}
Upvotes: 1
Reputation: 751
probably you don tneed it anymore, but instead of create a stub i just used spyOn and it worked like a charm.
Upvotes: 1
Reputation: 4172
When you say, "I want to use signInWithEmailAndPassword function in my mocha unit test" then I would say to you, "why"?
Are you trying to help out the Firebase team by testing that their authentication service works? That's nice of you, but if you want to test YOUR app then you should NOT be calling out to firebase at all in a unit test. What you really want to check is that a response similar to what Firebase responds with is handled correctly by your application in the code that is run once the response comes back.
If I were tasked with writing a test for this I would use the sinon library with mocha and create a stub that calls a different function which returns some data instead of actually calling to Firebase:
This illustrates the syntax for a sinon stub:
var stub = sinon.stub(object, "method", func);
This is what I would do in your example:
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"
}
});
Upvotes: 4