Last active
July 13, 2016 08:04
-
-
Save ivawzh/5b131a314bd0e2d473f85fd17ada2fab to your computer and use it in GitHub Desktop.
Firebase test helper as a set up util for npm lib 'firebase-server'.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import proxyquire from 'proxyquire' | |
import originalWebsocket from 'faye-websocket' | |
import FirebaseServer from 'firebase-server' | |
const localhostWS = { | |
'faye-websocket': { | |
'@global': true, | |
Client: url => { | |
const localhostUrl = url.replace(/dummy\d+\.firebaseio\.test/i, 'localhost') | |
return new originalWebsocket.Client(localhostUrl) | |
} | |
} | |
} | |
// Firebase has strict requirements about the hostname format. So we provide a dummy | |
// hostname and then change the URL to localhost inside the faye-websocket's Client | |
// constructor. | |
const firebase = proxyquire('firebase', localhostWS) | |
// Turn this on if you want to see the useless Firebase logs | |
firebase.database.enableLogging(false) | |
let sequentialConnectionId = 0 | |
// Fake Firebase apps are identified by port numbers, | |
// i.e. use different port numbers when you want to support multiple apps. | |
export function newFirebaseClient(port, authToken) { | |
const name = 'test-firebase-client-' + sequentialConnectionId | |
const url = 'ws://dummy' + (sequentialConnectionId++) + '.firebaseio.test:' + port | |
const config = { | |
databaseURL: url, | |
serviceAccount: { | |
'private_key': 'fake', | |
'client_email': 'fake' | |
} | |
} | |
overwriteAuth(authToken) | |
const app = firebase.initializeApp(config, name) | |
return app.database() | |
} | |
// Override Firebase client authentication mechanism. This allows us to set custom auth tokens during | |
// tests, as well as authenticate anonymously. | |
function overwriteAuth(token) { | |
firebase.INTERNAL.factories.auth = (app, extendApp) => { | |
const _listeners = [] | |
extendApp({ | |
'INTERNAL': { | |
'getToken': () => { | |
if (!token) { | |
return Promise.resolve(null) | |
} | |
_listeners.forEach(listener => { | |
listener(token) | |
}) | |
return Promise.resolve({ accessToken: token, expirationTime: 1566618502074 }) | |
}, | |
'addAuthTokenListener': listener => { | |
_listeners.push(listener) | |
} | |
} | |
}) | |
} | |
} | |
export function setupDatabase(port, data, authToken) { | |
const server = new FirebaseServer(port, 'localhost:' + port, data) | |
const client = newFirebaseClient(port, authToken) | |
return { server, client } | |
} | |
export function destroyDatabase(server, client) { | |
client.goOffline() | |
server.close() | |
server = null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment