diff --git a/.gitignore b/.gitignore index 3bcdc962..787bcd1a 100644 --- a/.gitignore +++ b/.gitignore @@ -14,16 +14,19 @@ xcuserdata/ # Android # Built application files -android/*/build/ +**/android/**/build/ # Crashlytics configuations android/com_crashlytics_export_strings.xml +# Signing files +android/.signing/ + # Local configuration file (sdk path, etc) -android/local.properties +**/android/local.properties # Gradle generated files -android/.gradle/ +**/android/.gradle/ # Signing files android/.signing/ @@ -41,7 +44,7 @@ android/.idea/misc.xml android/.idea/modules.xml android/.idea/scopes/scope_settings.xml android/.idea/vcs.xml -android/*.iml +**/android/**/*.iml ios/RnFirebase.xcodeproj/xcuserdata # OS-specific files @@ -54,9 +57,24 @@ ehthumbs.db Thumbs.dbandroid/gradle android/gradlew android/build +android/.gradle android/gradlew.bat -android/gradle/ -.idea +android/gradle +lib/.watchmanconfig .idea coverage yarn.lock + +tests/build +tests/ios/Podfile.lock +tests/android/app/build +tests/ios/Pods +tests/ios/Podfile.lock +tests/firebase +.gradle +local.properties +*.iml + +**/ios/Pods/** +**/ios/ReactNativeFirebaseDemo.xcworkspace/ + diff --git a/.npmignore b/.npmignore index 8d5f96d6..4d657ee4 100644 --- a/.npmignore +++ b/.npmignore @@ -60,3 +60,6 @@ docs .idea coverage yarn.lock +tests +lib/.watchmanconfig + diff --git a/README.md b/README.md index 94c7e3bf..5cbd3754 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# React Native Firebase +# React Native Firebase [![Chat](https://img.shields.io/badge/chat-on%20discord-7289da.svg)](https://discord.gg/t6bdqMs) [![Gitter](https://badges.gitter.im/invertase/react-native-firebase.svg)](https://gitter.im/invertase/react-native-firebase?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) @@ -6,15 +6,19 @@ [![License](https://img.shields.io/npm/l/react-native-firebase.svg)](/LICENSE) **RNFirebase** makes using [Firebase](http://firebase.com) with React Native simple. + +> [Documentation](https://invertase.io/react-native-firebase) + +
### Install -``` +```bash npm i react-native-firebase --save ``` #### Platform specific setup guides: -[![ios](https://a.fsdn.com/sd/topics/ios_64.png)](docs/installation.ios.md) [![android](https://a.fsdn.com/sd/topics/android_64.png)](docs/installation.android.md) +[![ios](https://a.fsdn.com/sd/topics/ios_64.png)](http://invertase.io/react-native-firebase/#/installation-ios) [![android](https://a.fsdn.com/sd/topics/android_64.png)](http://invertase.io/react-native-firebase/#/installation-android)
@@ -30,47 +34,6 @@ The native SDKs also allow us to hook into device sdk's which are not possible w
-### Test app - -To help ensure changes and features work across both iOS & Android, we've developed an app specifically to test `react-native-firebase` against the [`firebase` web SDK](https://www.npmjs.com/package/firebase). Please see the [`react-native-firebase-tests`](https://github.com/invertase/react-native-firebase-tests) repository for more information. - -
- -### Examples app - -There's currently a work in progress [examples app](https://github.com/invertase/react-native-firebase-examples) which aims to demonstrate various real world use-case scenarios with React Native & Firebase. We welcome any new examples or updates to existing ones. - -
- -### Documentation - -RNFirebase aims to replicate the Firebase Web SDK as closely as possible. Because of this, the documentation focuses around the installation, differences & best practices of this library. Please see the [Firebase Web SDK](https://firebase.google.com/docs/reference/js/) documentation for Firebase functionality. - -> If you find any discrepancies between the two libraries, please raise an issue or PR. - -* [Firebase Setup](docs/firebase-setup.md) -* API - * [Authentication](docs/api/authentication.md) - * [Realtime Database](docs/api/database.md) - * [Analytics](docs/api/analytics.md) - * [Storage](docs/api/storage.md) - * [Messaging](docs/api/cloud-messaging.md) - * [Crash](docs/api/crash.md) - * [Transactions](docs/api/transactions.md) -* [FAQs / Troubleshooting](docs/faqs.md) - -
- -### Contributing - -We welcome any contribution to the repository. Please ensure your changes to the JavaScript code follow the styling guides controlled by ESlint. Changes to native code should be kept clean and follow the standard of existing code. - -Changes to existing code should ensure all relevant tests on the test app pass. Any new features should have new tests created and ensure all existing tests pass. - -**Project board:** https://github.com/invertase/react-native-firebase/projects - -
- ### License - MIT diff --git a/RNFirebase.podspec b/RNFirebase.podspec index 331fb005..b509a3f4 100644 --- a/RNFirebase.podspec +++ b/RNFirebase.podspec @@ -6,7 +6,7 @@ Pod::Spec.new do |s| s.version = package["version"] s.summary = package["description"] s.description = <<-DESC - Wanna integrate firebase into your app using React Native? + Integrate firebase into your app using the React Native SDKs. DESC s.homepage = "http://invertase.io" s.license = package['license'] @@ -16,11 +16,4 @@ Pod::Spec.new do |s| s.platform = :ios, "8.0" s.preserve_paths = 'README.md', 'package.json', '*.js' s.source_files = 'ios/RNFirebase/*.{h,m}' - s.dependency 'React' - s.dependency 'Firebase/Auth' - s.dependency 'Firebase/Core' - s.dependency 'Firebase/Database' - s.dependency 'Firebase/Messaging' - s.dependency 'Firebase/RemoteConfig' - s.dependency 'Firebase/Storage' end diff --git a/android/src/main/java/io/invertase/firebase/Utils.java b/android/src/main/java/io/invertase/firebase/Utils.java index f52241bd..424cbc3c 100644 --- a/android/src/main/java/io/invertase/firebase/Utils.java +++ b/android/src/main/java/io/invertase/firebase/Utils.java @@ -78,12 +78,13 @@ public class Utils { /** * * @param name + * @param refId + * @param listenerId * @param path - * @param modifiersString * @param dataSnapshot * @return */ - public static WritableMap snapshotToMap(String name, String path, String modifiersString, DataSnapshot dataSnapshot) { + public static WritableMap snapshotToMap(String name, int refId, Integer listenerId, String path, DataSnapshot dataSnapshot) { WritableMap snapshot = Arguments.createMap(); WritableMap eventMap = Arguments.createMap(); @@ -106,10 +107,13 @@ public class Utils { snapshot.putArray("childKeys", Utils.getChildKeys(dataSnapshot)); mapPutValue("priority", dataSnapshot.getPriority(), snapshot); + eventMap.putInt("refId", refId); + if (listenerId != null) { + eventMap.putInt("listenerId", listenerId); + } eventMap.putString("path", path); eventMap.putMap("snapshot", snapshot); eventMap.putString("eventName", name); - eventMap.putString("modifiersString", modifiersString); return eventMap; } diff --git a/android/src/main/java/io/invertase/firebase/database/RNFirebaseDatabase.java b/android/src/main/java/io/invertase/firebase/database/RNFirebaseDatabase.java index c722d0f3..c06e7ee2 100644 --- a/android/src/main/java/io/invertase/firebase/database/RNFirebaseDatabase.java +++ b/android/src/main/java/io/invertase/firebase/database/RNFirebaseDatabase.java @@ -34,7 +34,7 @@ import io.invertase.firebase.Utils; public class RNFirebaseDatabase extends ReactContextBaseJavaModule { private static final String TAG = "RNFirebaseDatabase"; - private HashMap mDBListeners = new HashMap<>(); + private HashMap mReferences = new HashMap<>(); private HashMap mTransactionHandlers = new HashMap<>(); private FirebaseDatabase mFirebaseDatabase; @@ -264,7 +264,7 @@ public class RNFirebaseDatabase extends ReactContextBaseJavaModule { } /** - * + * * @param id * @param updates */ @@ -279,61 +279,60 @@ public class RNFirebaseDatabase extends ReactContextBaseJavaModule { } @ReactMethod - public void on(final String path, final String modifiersString, final ReadableArray modifiersArray, final String eventName, final Callback callback) { - RNFirebaseDatabaseReference ref = this.getDBHandle(path, modifiersArray, modifiersString); + public void on(final int refId, final String path, final ReadableArray modifiers, final int listenerId, final String eventName, final Callback callback) { + RNFirebaseDatabaseReference ref = this.getDBHandle(refId, path, modifiers); if (eventName.equals("value")) { - ref.addValueEventListener(); + ref.addValueEventListener(listenerId); } else { - ref.addChildEventListener(eventName); + ref.addChildEventListener(listenerId, eventName); } WritableMap resp = Arguments.createMap(); resp.putString("status", "success"); + resp.putInt("refId", refId); resp.putString("handle", path); callback.invoke(null, resp); } @ReactMethod - public void once(final String path, final String modifiersString, final ReadableArray modifiersArray, final String eventName, final Callback callback) { - RNFirebaseDatabaseReference ref = this.getDBHandle(path, modifiersArray, modifiersString); + public void once(final int refId, final String path, final ReadableArray modifiers, final String eventName, final Callback callback) { + RNFirebaseDatabaseReference ref = this.getDBHandle(refId, path, modifiers); ref.addOnceValueEventListener(callback); } /** * At the time of this writing, off() only gets called when there are no more subscribers to a given path. - * `mListeners` might therefore be out of sync (though javascript isnt listening for those eventTypes, so + * `mListeners` might therefore be out of sync (though javascript isnt listening for those eventNames, so * it doesn't really matter- just polluting the RN bridge a little more than necessary. * off() should therefore clean *everything* up */ @ReactMethod public void off( - final String path, - final String modifiersString, - final String eventName, + final int refId, + final ReadableArray listeners, final Callback callback) { - String key = this.getDBListenerKey(path, modifiersString); - RNFirebaseDatabaseReference r = mDBListeners.get(key); + RNFirebaseDatabaseReference r = mReferences.get(refId); if (r != null) { - if (eventName == null || "".equals(eventName)) { - r.cleanup(); - mDBListeners.remove(key); - } else { - r.removeEventListener(eventName); + List listenersList = Utils.recursivelyDeconstructReadableArray(listeners); + + for (Object l : listenersList) { + Map listener = (Map) l; + int listenerId = ((Double) listener.get("listenerId")).intValue(); + String eventName = (String) listener.get("eventName"); + r.removeEventListener(listenerId, eventName); if (!r.hasListeners()) { - mDBListeners.remove(key); + mReferences.remove(refId); } } } - Log.d(TAG, "Removed listener " + path + "/" + modifiersString); + Log.d(TAG, "Removed listeners refId: " + refId + " ; count: " + listeners.size()); WritableMap resp = Arguments.createMap(); - resp.putString("handle", path); + resp.putInt("refId", refId); resp.putString("status", "success"); - resp.putString("modifiersString", modifiersString); - //TODO: Remaining listeners callback.invoke(null, resp); } @@ -440,23 +439,19 @@ public class RNFirebaseDatabase extends ReactContextBaseJavaModule { } } - private RNFirebaseDatabaseReference getDBHandle(final String path, final ReadableArray modifiersArray, final String modifiersString) { - String key = this.getDBListenerKey(path, modifiersString); - RNFirebaseDatabaseReference r = mDBListeners.get(key); + private RNFirebaseDatabaseReference getDBHandle(final int refId, final String path, + final ReadableArray modifiers) { + RNFirebaseDatabaseReference r = mReferences.get(refId); if (r == null) { ReactContext ctx = getReactApplicationContext(); - r = new RNFirebaseDatabaseReference(ctx, mFirebaseDatabase, path, modifiersArray, modifiersString); - mDBListeners.put(key, r); + r = new RNFirebaseDatabaseReference(ctx, mFirebaseDatabase, refId, path, modifiers); + mReferences.put(refId, r); } return r; } - private String getDBListenerKey(String path, String modifiersString) { - return path + " | " + modifiersString; - } - @Override public Map getConstants() { final Map constants = new HashMap<>(); diff --git a/android/src/main/java/io/invertase/firebase/database/RNFirebaseDatabaseReference.java b/android/src/main/java/io/invertase/firebase/database/RNFirebaseDatabaseReference.java index d5cb857c..45ce7504 100644 --- a/android/src/main/java/io/invertase/firebase/database/RNFirebaseDatabaseReference.java +++ b/android/src/main/java/io/invertase/firebase/database/RNFirebaseDatabaseReference.java @@ -1,9 +1,11 @@ package io.invertase.firebase.database; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import android.util.Log; +import java.util.Map; import java.util.Set; import com.facebook.react.bridge.Callback; @@ -25,81 +27,87 @@ public class RNFirebaseDatabaseReference { private static final String TAG = "RNFirebaseDBReference"; private Query mQuery; + private int mRefId; private String mPath; - private String mModifiersString; - private ChildEventListener mEventListener; - private ValueEventListener mValueListener; + private Map mChildEventListeners = new HashMap<>(); + private Map mValueEventListeners = new HashMap<>(); private ReactContext mReactContext; - private Set childEventListeners = new HashSet<>(); public RNFirebaseDatabaseReference(final ReactContext context, - final FirebaseDatabase firebaseDatabase, - final String path, - final ReadableArray modifiersArray, - final String modifiersString) { + final FirebaseDatabase firebaseDatabase, + final int refId, + final String path, + final ReadableArray modifiersArray) { mReactContext = context; + mRefId = refId; mPath = path; - mModifiersString = modifiersString; mQuery = this.buildDatabaseQueryAtPathAndModifiers(firebaseDatabase, path, modifiersArray); } - public void addChildEventListener(final String eventName) { - if (mEventListener == null) { - mEventListener = new ChildEventListener() { + public void addChildEventListener(final int listenerId, final String eventName) { + if (!mChildEventListeners.containsKey(listenerId)) { + ChildEventListener childEventListener = new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) { - handleDatabaseEvent("child_added", dataSnapshot); + if ("child_added".equals(eventName)) { + handleDatabaseEvent("child_added", listenerId, dataSnapshot); + } } @Override public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) { - handleDatabaseEvent("child_changed", dataSnapshot); + if ("child_changed".equals(eventName)) { + handleDatabaseEvent("child_changed", listenerId, dataSnapshot); + } } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { - handleDatabaseEvent("child_removed", dataSnapshot); + if ("child_removed".equals(eventName)) { + handleDatabaseEvent("child_removed", listenerId, dataSnapshot); + } } @Override public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) { - handleDatabaseEvent("child_moved", dataSnapshot); + if ("child_moved".equals(eventName)) { + handleDatabaseEvent("child_moved", listenerId, dataSnapshot); + } } @Override public void onCancelled(DatabaseError error) { - removeChildEventListener(); - handleDatabaseError(error); + removeChildEventListener(listenerId); + handleDatabaseError(listenerId, error); } }; - mQuery.addChildEventListener(mEventListener); - Log.d(TAG, "Added ChildEventListener for path: " + mPath + " with modifiers: "+ mModifiersString); + mChildEventListeners.put(listenerId, childEventListener); + mQuery.addChildEventListener(childEventListener); + Log.d(TAG, "Added ChildEventListener for refId: " + mRefId + " listenerId: " + listenerId); } else { - Log.w(TAG, "Trying to add duplicate ChildEventListener for path: " + mPath + " with modifiers: "+ mModifiersString); + Log.d(TAG, "ChildEventListener for refId: " + mRefId + " listenerId: " + listenerId + " already exists"); } - //Keep track of the events that the JS is interested in knowing about - childEventListeners.add(eventName); } - public void addValueEventListener() { - if (mValueListener == null) { - mValueListener = new ValueEventListener() { + public void addValueEventListener(final int listenerId) { + if (!mValueEventListeners.containsKey(listenerId)) { + ValueEventListener valueEventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { - handleDatabaseEvent("value", dataSnapshot); + handleDatabaseEvent("value", listenerId, dataSnapshot); } @Override public void onCancelled(DatabaseError error) { - removeValueEventListener(); - handleDatabaseError(error); + removeValueEventListener(listenerId); + handleDatabaseError(listenerId, error); } }; - mQuery.addValueEventListener(mValueListener); - Log.d(TAG, "Added ValueEventListener for path: " + mPath + " with modifiers: "+ mModifiersString); - //this.setListeningTo(mPath, modifiersString, "value"); + mValueEventListeners.put(listenerId, valueEventListener); + mQuery.addValueEventListener(valueEventListener); + Log.d(TAG, "Added ValueEventListener for refId: " + mRefId + " listenerId: " + listenerId); } else { - Log.w(TAG, "Trying to add duplicate ValueEventListener for path: " + mPath + " with modifiers: "+ mModifiersString); + Log.d(TAG, "ValueEventListener for refId: " + mRefId + " listenerId: " + listenerId + " already exists"); } } @@ -107,63 +115,59 @@ public class RNFirebaseDatabaseReference { final ValueEventListener onceValueEventListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { - WritableMap data = Utils.snapshotToMap("value", mPath, mModifiersString, dataSnapshot); + WritableMap data = Utils.snapshotToMap("value", mRefId, null, mPath, dataSnapshot); callback.invoke(null, data); } @Override public void onCancelled(DatabaseError error) { WritableMap err = Arguments.createMap(); + err.putInt("refId", mRefId); err.putString("path", mPath); err.putInt("code", error.getCode()); - err.putString("modifiers", mModifiersString); err.putString("details", error.getDetails()); err.putString("message", error.getMessage()); callback.invoke(err); } }; mQuery.addListenerForSingleValueEvent(onceValueEventListener); - Log.d(TAG, "Added OnceValueEventListener for path: " + mPath + " with modifiers " + mModifiersString); + Log.d(TAG, "Added OnceValueEventListener for refId: " + mRefId); } - public void removeEventListener(String eventName) { + public void removeEventListener(int listenerId, String eventName) { if ("value".equals(eventName)) { - this.removeValueEventListener(); + this.removeValueEventListener(listenerId); } else { - childEventListeners.remove(eventName); - if (childEventListeners.isEmpty()) { - this.removeChildEventListener(); - } + this.removeChildEventListener(listenerId); } } public boolean hasListeners() { - return mEventListener != null || mValueListener != null; + return !mChildEventListeners.isEmpty() || !mValueEventListeners.isEmpty(); } public void cleanup() { Log.d(TAG, "cleaning up database reference " + this); - childEventListeners.clear(); - this.removeChildEventListener(); - this.removeValueEventListener(); + this.removeChildEventListener(null); + this.removeValueEventListener(null); } - private void removeChildEventListener() { - if (mEventListener != null) { - mQuery.removeEventListener(mEventListener); - mEventListener = null; + private void removeChildEventListener(Integer listenerId) { + ChildEventListener listener = mChildEventListeners.remove(listenerId); + if (listener != null) { + mQuery.removeEventListener(listener); } } - private void removeValueEventListener() { - if (mValueListener != null) { - mQuery.removeEventListener(mValueListener); - mValueListener = null; + private void removeValueEventListener(Integer listenerId) { + ValueEventListener listener = mValueEventListeners.remove(listenerId); + if (listener != null) { + mQuery.removeEventListener(listener); } } - private void handleDatabaseEvent(final String name, final DataSnapshot dataSnapshot) { - WritableMap data = Utils.snapshotToMap(name, mPath, mModifiersString, dataSnapshot); + private void handleDatabaseEvent(final String name, final Integer listenerId, final DataSnapshot dataSnapshot) { + WritableMap data = Utils.snapshotToMap(name, mRefId, listenerId, mPath, dataSnapshot); WritableMap evt = Arguments.createMap(); evt.putString("eventName", name); evt.putMap("body", data); @@ -171,12 +175,15 @@ public class RNFirebaseDatabaseReference { Utils.sendEvent(mReactContext, "database_event", evt); } - private void handleDatabaseError(final DatabaseError error) { + private void handleDatabaseError(final Integer listenerId, final DatabaseError error) { WritableMap errMap = Arguments.createMap(); + errMap.putInt("refId", mRefId); + if (listenerId != null) { + errMap.putInt("listenerId", listenerId); + } errMap.putString("path", mPath); errMap.putInt("code", error.getCode()); - errMap.putString("modifiers", mModifiersString); errMap.putString("details", error.getDetails()); errMap.putString("message", error.getMessage()); @@ -187,104 +194,102 @@ public class RNFirebaseDatabaseReference { final String path, final ReadableArray modifiers) { Query query = firebaseDatabase.getReference(path); - List strModifiers = Utils.recursivelyDeconstructReadableArray(modifiers); + List modifiersList = Utils.recursivelyDeconstructReadableArray(modifiers); - for (Object strModifier : strModifiers) { - String str = (String) strModifier; + for (Object m : modifiersList) { + Map modifier = (Map) m; + String type = (String) modifier.get("type"); + String name = (String) modifier.get("name"); - String[] strArr = str.split(":"); - String methStr = strArr[0]; - - if (methStr.equalsIgnoreCase("orderByKey")) { - query = query.orderByKey(); - } else if (methStr.equalsIgnoreCase("orderByValue")) { - query = query.orderByValue(); - } else if (methStr.equalsIgnoreCase("orderByPriority")) { - query = query.orderByPriority(); - } else if (methStr.contains("orderByChild")) { - String key = strArr[1]; - Log.d(TAG, "orderByChild: " + key); - query = query.orderByChild(key); - } else if (methStr.contains("limitToLast")) { - String key = strArr[1]; - int limit = Integer.parseInt(key); - Log.d(TAG, "limitToLast: " + limit); - query = query.limitToLast(limit); - } else if (methStr.contains("limitToFirst")) { - String key = strArr[1]; - int limit = Integer.parseInt(key); - Log.d(TAG, "limitToFirst: " + limit); - query = query.limitToFirst(limit); - } else if (methStr.contains("equalTo")) { - String value = strArr[1]; - String type = strArr[2]; - if ("number".equals(type)) { - double doubleValue = Double.parseDouble(value); - if (strArr.length > 3) { - query = query.equalTo(doubleValue, strArr[3]); - } else { - query = query.equalTo(doubleValue); - } - } else if ("boolean".equals(type)) { - boolean booleanValue = Boolean.parseBoolean(value); - if (strArr.length > 3) { - query = query.equalTo(booleanValue, strArr[3]); - } else { - query = query.equalTo(booleanValue); - } - } else { - if (strArr.length > 3) { - query = query.equalTo(value, strArr[3]); - } else { - query = query.equalTo(value); - } + if ("orderBy".equals(type)) { + if ("orderByKey".equals(name)) { + query = query.orderByKey(); + } else if ("orderByPriority".equals(name)) { + query = query.orderByPriority(); + } else if ("orderByValue".equals(name)) { + query = query.orderByValue(); + } else if ("orderByChild".equals(name)) { + String key = (String) modifier.get("key"); + query = query.orderByChild(key); } - } else if (methStr.contains("endAt")) { - String value = strArr[1]; - String type = strArr[2]; - if ("number".equals(type)) { - double doubleValue = Double.parseDouble(value); - if (strArr.length > 3) { - query = query.endAt(doubleValue, strArr[3]); - } else { - query = query.endAt(doubleValue); - } - } else if ("boolean".equals(type)) { - boolean booleanValue = Boolean.parseBoolean(value); - if (strArr.length > 3) { - query = query.endAt(booleanValue, strArr[3]); - } else { - query = query.endAt(booleanValue); - } - } else { - if (strArr.length > 3) { - query = query.endAt(value, strArr[3]); - } else { - query = query.endAt(value); - } + } else if ("limit".equals(type)) { + int limit = ((Double)modifier.get("limit")).intValue(); + if ("limitToLast".equals(name)) { + query = query.limitToLast(limit); + } else if ("limitToFirst".equals(name)) { + query = query.limitToFirst(limit); } - } else if (methStr.contains("startAt")) { - String value = strArr[1]; - String type = strArr[2]; - if ("number".equals(type)) { - double doubleValue = Double.parseDouble(value); - if (strArr.length > 3) { - query = query.startAt(doubleValue, strArr[3]); - } else { - query = query.startAt(doubleValue); + } else if ("filter".equals(type)) { + String valueType = (String) modifier.get("valueType"); + String key = (String) modifier.get("key"); + if ("equalTo".equals(name)) { + if ("number".equals(valueType)) { + double value = (Double) modifier.get("value"); + if (key == null) { + query = query.equalTo(value); + } else { + query = query.equalTo(value, key); + } + } else if ("boolean".equals(valueType)) { + boolean value = (Boolean) modifier.get("value"); + if (key == null) { + query = query.equalTo(value); + } else { + query = query.equalTo(value, key); + } + } else if ("string".equals(valueType)) { + String value = (String) modifier.get("value"); + if (key == null) { + query = query.equalTo(value); + } else { + query = query.equalTo(value, key); + } } - } else if ("boolean".equals(type)) { - boolean booleanValue = Boolean.parseBoolean(value); - if (strArr.length > 3) { - query = query.startAt(booleanValue, strArr[3]); - } else { - query = query.startAt(booleanValue); + } else if ("endAt".equals(name)) { + if ("number".equals(valueType)) { + double value = (Double) modifier.get("value"); + if (key == null) { + query = query.endAt(value); + } else { + query = query.endAt(value, key); + } + } else if ("boolean".equals(valueType)) { + boolean value = (Boolean) modifier.get("value"); + if (key == null) { + query = query.endAt(value); + } else { + query = query.endAt(value, key); + } + } else if ("string".equals(valueType)) { + String value = (String) modifier.get("value"); + if (key == null) { + query = query.endAt(value); + } else { + query = query.endAt(value, key); + } } - } else { - if (strArr.length > 3) { - query = query.startAt(value, strArr[3]); - } else { - query = query.startAt(value); + } else if ("startAt".equals(name)) { + if ("number".equals(valueType)) { + double value = (Double) modifier.get("value"); + if (key == null) { + query = query.startAt(value); + } else { + query = query.startAt(value, key); + } + } else if ("boolean".equals(valueType)) { + boolean value = (Boolean) modifier.get("value"); + if (key == null) { + query = query.startAt(value); + } else { + query = query.startAt(value, key); + } + } else if ("string".equals(valueType)) { + String value = (String) modifier.get("value"); + if (key == null) { + query = query.startAt(value); + } else { + query = query.startAt(value, key); + } } } } diff --git a/docs/.nojekyll b/docs/.nojekyll new file mode 100644 index 00000000..e69de29b diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 00000000..a2c60da3 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,25 @@ + +

+
+ + React Native Firebase +

+ +
+[![Chat](https://img.shields.io/badge/chat-on%20discord-7289da.svg)](https://discord.gg/t6bdqMs) +[![Gitter](https://badges.gitter.im/invertase/react-native-firebase.svg)](https://gitter.im/invertase/react-native-firebase?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) +[![npm version](https://img.shields.io/npm/v/react-native-firebase.svg)](https://www.npmjs.com/package/react-native-firebase) +[![License](https://img.shields.io/npm/l/react-native-firebase.svg)](/LICENSE) +
+A well tested Firebase implementation for React Native, supporting both iOS & Android apps. +
+ +--- + +RNFirebase is a _light-weight_ layer sitting on-top of the native Firebase libraries for both iOS and Android which mirrors the Firebase Web SDK as closely as possible. + +Although the [Firebase Web SDK](https://www.npmjs.com/package/firebase) library will work with React Native, it is mainly built for the web. + +RNFirebase provides a JavaScript bridge to the native Firebase SDKs for both iOS and Android. Firebase will run on the native thread, allowing the rest of your app to run on the [JS thread](https://facebook.github.io/react-native/docs/performance.html#javascript-frame-rate). The Firebase Web SDK also runs on the JS thread, therefore potentially affecting the frame rate causing jank with animations, touch events etc. All in all, RNFirebase provides much faster performance (~2x) over the web SDK. + +The native SDKs also allow us to hook into device sdk's which are not possible with the web SDK, for example crash reporting, offline realtime database support, analyics and more! diff --git a/docs/_sidebar.md b/docs/_sidebar.md new file mode 100644 index 00000000..1a3742eb --- /dev/null +++ b/docs/_sidebar.md @@ -0,0 +1,25 @@ +- Getting started + - [Installation - iOS](/installation-ios) + - [Installation - Android](/installation-android) + - [Firebase Setup](/firebase-setup.md) + - [Usage](/usage) + +- Contributing + - [Guidelines](/contributing/guidelines) + - [Testing](/contributing/testing) + +- Modules + - [Authentication](/modules/authentication) + - [Realtime Database](/modules/database) + - [Analytics](/modules/analytics) + - [Storage](/modules/storage) + - [Cloud Messaging](/modules/cloud-messaging) + - [Crash Reporting](/modules/crash) + - [Transactions](/modules/transactions) + +- Other + - [Project Board](https://github.com/invertase/react-native-firebase/projects) + - [FAQs / Troubleshooting](/faqs) + - [Examples](https://github.com/invertase/react-native-firebase-examples) + - [Chat](https://discord.gg/t6bdqMs) + - [Gitter](https://gitter.im/invertase/react-native-firebase) diff --git a/docs/api/remote-config.md b/docs/api/remote-config.md deleted file mode 100644 index 413c634a..00000000 --- a/docs/api/remote-config.md +++ /dev/null @@ -1 +0,0 @@ -# Remote Config diff --git a/docs/api/transactions.md b/docs/api/transactions.md deleted file mode 100644 index 64ab1f3f..00000000 --- a/docs/api/transactions.md +++ /dev/null @@ -1,23 +0,0 @@ -# Transactions - -Transactions are currently an experimental feature as they can not be integrated as easily as the other Firebase features. Please see the [Firebase documentation](https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction) for full implemtation details. - -## Example - -```javascript -const ref = firebase.database().ref('user/posts'); - -ref.transaction((posts) => { - return (posts || 0) + 1; -}, (error, committed, snapshot) => { - if (error) { - console.log('Something went wrong', error); - } else if (!committed) { - console.log('Aborted'); // Returning undefined will trigger this - } else { - console.log('User posts incremented by 1'); - } - - console.log('User posts is now: ', snapshot.val()); -}); -``` diff --git a/docs/contributing/guidelines.md b/docs/contributing/guidelines.md new file mode 100644 index 00000000..c7b8ad3c --- /dev/null +++ b/docs/contributing/guidelines.md @@ -0,0 +1,5 @@ +# Guidelines + +We welcome any contribution to the repository. Please ensure your changes to the JavaScript code follow the styling guides controlled by ESlint. Changes to native code should be kept clean and follow the standard of existing code. + +Changes to existing code should ensure all relevant tests on the test app pass. Any new features should have new tests created and ensure all existing tests pass. diff --git a/docs/contributing/testing.md b/docs/contributing/testing.md new file mode 100644 index 00000000..383062db --- /dev/null +++ b/docs/contributing/testing.md @@ -0,0 +1,3 @@ +# Testing + + diff --git a/docs/faqs.md b/docs/faqs.md index 288fcd03..14f77151 100644 --- a/docs/faqs.md +++ b/docs/faqs.md @@ -1,6 +1,6 @@ # FAQs / Troubleshooting -### Comparison to Firestack +## Comparison to Firestack Firestack was a great start to integrating Firebase and React Native, however has underlying issues which needed to be fixed. A V3 fork of Firestack was created to help address issues such as lack of standardisation with the Firebase Web SDK, @@ -10,7 +10,7 @@ too large to manage on the existing repository, whilst trying to maintain backwa RNFirebase was re-written from the ground up, addressing these issues with core focus being around matching the Web SDK as closely as possible and fixing the major bugs/issues along the way. -### How do I integrate Redux with RNFirebase +## How do I integrate Redux with RNFirebase As every project has different requirements & structure, RNFirebase *currently* has no built in methods for Redux integration. As RNFirebase can be used outside of a Components context, you do have free reign to integrate it as you see fit. For example, @@ -42,7 +42,7 @@ export function onAuthStateChanged() { } ``` -### [Android] Google Play Services related issues +## [Android] Google Play Services related issues The firebase SDK requires a certain version of Google Play Services installed on Android in order to function properly. @@ -68,7 +68,7 @@ party emulator such as GenyMotion. Using this kind of workaround with Google Play Services can be problematic, so we recommend using the native Android Studio emulators to reduce the chance of these complications. -### [Android] Turning off Google Play Services availability errors +## [Android] Turning off Google Play Services availability errors G.P.S errors can be turned off using a config option like so: @@ -79,7 +79,7 @@ const firebase = RNFirebase.initializeApp({ ``` This will stop your app from immediately red-boxing or crashing, but won't solve the underlying issue of G.P.S not being available or of the correct version. This will mean certain functionalities won't work properly and your app may even crash. -### [Android] Checking for Google Play Services availability with React Native Firebase +## [Android] Checking for Google Play Services availability with React Native Firebase React Native Firebase actually has a useful helper object for checking G.P.S availability: @@ -109,7 +109,7 @@ This error will match the messages and error codes mentioned above, and can be f https://developers.google.com/android/reference/com/google/android/gms/common/ConnectionResult#SERVICE_VERSION_UPDATE_REQUIRED -### [Android] Duplicate Dex Files error (build time error) +## [Android] Duplicate Dex Files error (build time error) A common build time error when using libraries that require google play services is of the form: 'Failed on android with com.android.dex.DexException: Multiple dex files... ' diff --git a/docs/firebase-setup.md b/docs/firebase-setup.md index 3407d0ba..d28b493b 100644 --- a/docs/firebase-setup.md +++ b/docs/firebase-setup.md @@ -4,51 +4,17 @@ The RNFirebase library is intended on making it easy to work with [Firebase](htt To add Firebase to your project, make sure to create a project in the [Firebase console](https://firebase.google.com/console) -![Create a new project](http://d.pr/i/17cJ2.png) +![Create a new project](https://i.imgur.com/KbbamwD.png) Each platform uses a different setup method after creating the project. ## iOS -See the [ios setup guide](./installation.ios.md). +For iOS, ensure you've followed the instructions provided by Firebase; adding your [GoogleService-Info.plist](https://github.com/invertase/react-native-firebase/blob/master/tests/ios/GoogleService-Info.plist) +file to the project, and [configuring your AppDelegate](https://github.com/invertase/react-native-firebase/blob/master/tests/ios/ReactNativeFirebaseDemo/AppDelegate.m#L20). ## Android -See the [android setup guide](./installation.android.md). - -## Usage - -After creating a Firebase project and installing the library, we can use it in our project by importing the library in our JavaScript: - -```javascript -import RNFirebase from 'react-native-firebase' -``` - -We need to tell the Firebase library we want to _configure_ the project. RNFirebase provides a way to configure both the native and the JavaScript side of the project at the same time with a single command: - -```javascript -const firebase = RNFirebase.initializeApp({ - // config options -}); -``` - -### Configuration Options - -| option | type | Default Value | Description | -|----------------|----------|-------------------------|----------------------------------------| -| debug | bool | false | When set to true, RNFirebase will log messages to the console and fire `debug` events we can listen to in `js` | -| persistence | bool | false | When set to true, database persistence will be enabled. | - -For instance: - -```javascript -import RNFirebase from 'react-native-firebase'; - -const configurationOptions = { - debug: true -}; - -const firebase = RNFirebase.initializeApp(configurationOptions); - -export default firebase; -``` +For Android, ensure you've followed the instructions provided by Firebase; adding your [google-services.json](https://github.com/invertase/react-native-firebase/blob/master/tests/android/app/google-services.json) +file to the project, installing the [google-services](https://github.com/invertase/react-native-firebase/blob/master/tests/android/build.gradle#L9) + plugin and applying **at the end** of your [`build.gradle`](https://github.com/invertase/react-native-firebase/blob/master/tests/android/app/build.gradle#L144). diff --git a/docs/index.html b/docs/index.html new file mode 100644 index 00000000..8cbe0a0a --- /dev/null +++ b/docs/index.html @@ -0,0 +1,54 @@ + + + + + react-native-firebase - A react native firebase library supporting both android and ios native firebase SDK's + + + + + +
+ + + + + + + + + + + + + + diff --git a/docs/installation.android.md b/docs/installation-android.md similarity index 97% rename from docs/installation.android.md rename to docs/installation-android.md index 509bc91e..f1555ec1 100644 --- a/docs/installation.android.md +++ b/docs/installation-android.md @@ -1,6 +1,6 @@ # Android Installation -### 1 - Setup google-services.json +## 1) Setup google-services.json Download the `google-services.json` file provided by Firebase in the _Add Firebase to Android_ platform menu in your Firebase configuration console. This file should be downloaded to `YOUR_PROJECT/android/app/google-services.json`. Next you'll have to add the google-services gradle plugin in order to parse it. @@ -23,7 +23,7 @@ In your app build.gradle file, add the gradle plugin at the VERY BOTTOM of the f apply plugin: 'com.google.gms.google-services' ``` -### 2 - Link RNFirebase +## 2) Link RNFirebase To install `react-native-firebase` in your project, you'll need to import the package from `io.invertase.firebase` in your project's `android/app/src/main/java/com/[app name]/MainApplication.java` and list it as a package for ReactNative in the `getPackages()` function: @@ -61,7 +61,7 @@ include ':react-native-firebase' project(':react-native-firebase').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-firebase/android') ``` -### 3 - Cloud Messaging (optional) +## 3) Cloud Messaging (optional) If you plan on using [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging/), add the following to `android/app/src/main/AndroidManifest.xml`. diff --git a/docs/installation.ios.md b/docs/installation-ios.md similarity index 51% rename from docs/installation.ios.md rename to docs/installation-ios.md index 2ac49b9d..f9c17de5 100644 --- a/docs/installation.ios.md +++ b/docs/installation-ios.md @@ -1,9 +1,9 @@ -## iOS Installation +# iOS Installation -### 1 - Setup google-services.plist and dependencies +## 1) Setup google-services.plist and dependencies Setup the `google-services.plist` file and Firebase ios frameworks first; check out the relevant Firebase docs [here](https://firebase.google.com/docs/ios/setup#frameworks). -#### 1.1 - Initialisation +### 1.1) Initialisation Make sure you've added the following to the top of your `ios/[YOUR APP NAME]]/AppDelegate.m` file: `#import ` @@ -12,10 +12,11 @@ and this to the `didFinishLaunchingWithOptions:(NSDictionary *)launchOptions` me `[FIRApp configure];` -### 2 - Link RNFirebase +## 2) Link RNFirebase + There are multiple ways to install RNFirebase depending on how your project is currently setup: -#### 2.1 - Existing Cocoapods setup, including React Native as a pod +### 2.1) You already use Cocoapods and have React Native installed as a pod Simply add the following to your `Podfile`: ```ruby @@ -33,25 +34,27 @@ pod 'Firebase/Storage' pod 'RNFirebase', :path => '../node_modules/react-native-firebase' ``` -#### 2.2 - Via react-native-cli link +### 2.2) You're not using Cocoapods or don't have React Native installed as a pod (Automatic install) + React native ships with a `link` command that can be used to link the projects together, which can help automate the process of linking our package environments. ```bash react-native link react-native-firebase ``` +#### cocoapods + +We've automated the process of setting up with cocoapods. This will happen automatically upon linking the package with `react-native-cli`. + Update the newly installed pods once the linking is done: ```bash cd ios && pod update --verbose ``` -##### cocoapods -We've automated the process of setting up with cocoapods. This will happen automatically upon linking the package with `react-native-cli`. +**NOTE: You need to use the `ios/[YOUR APP NAME].xcworkspace` instead of the `ios/[YOUR APP NAME].xcproj` file from now on.** -**Remember to use the `ios/[YOUR APP NAME].xcworkspace` instead of the `ios/[YOUR APP NAME].xcproj` file from now on**. - -#### 2.3 - Manually +### 2.3) You're not using Cocoapods or don't have React Native installed as a pod (Manual install) If you prefer not to use `react-native link`, we can manually link the package together with the following steps, after `npm install`: @@ -90,4 +93,70 @@ pod 'Firebase/RemoteConfig' pod 'Firebase/Storage' ``` -Then you can run `(cd ios && pod install)` to get the pods opened. If you do use this route, remember to use the `.xcworkspace` file. +Then you can run `(cd ios && pod install)` to get the pods opened. + +**NOTE: You need to use the `ios/[YOUR APP NAME].xcworkspace` instead of the `ios/[YOUR APP NAME].xcproj` file from now on.** + +## 3) Cloud Messaging (optional) + +If you plan on using [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging/) then, you need to: + +**NOTE: FCM does not work on the iOS simulator, you must test is using a real device. This is a restriction enforced by Apple for some unknown reason.** + +### 3.1) Set up certificates + +Follow the instructions at https://firebase.google.com/docs/cloud-messaging/ios/certs + +### 3.2) Enable capabilities + +In Xcode, enable the following capabilities: + +1) Push Notifications +2) Background modes > Remove notifications + +### 3.3) Update `AppDelegate.h` + +Add the following import: + +`@import UserNotifications;` + +Change the interface descriptor to: + +`@interface AppDelegate : UIResponder ` + +### 3.4) Update `AppDelegate.m` + +Add the following import: + +`#import "RNFirebaseMessaging.h"` + +Add the following to the `didFinishLaunchingWithOptions:(NSDictionary *)launchOptions` method after `[FIRApp Configure]`: + +`[[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];` + +Add the following methods: + +```objectivec +- (void)userNotificationCenter:(UNUserNotificationCenter *)center + willPresentNotification:(UNNotification *)notification + withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler +{ + [RNFirebaseMessaging willPresentNotification:notification withCompletionHandler:completionHandler]; +} + +- (void)userNotificationCenter:(UNUserNotificationCenter *)center +didReceiveNotificationResponse:(UNNotificationResponse *)response + withCompletionHandler:(void (^)())completionHandler +{ + [RNFirebaseMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler]; +} + +-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { + [RNFirebaseMessaging didReceiveLocalNotification:notification]; +} + +- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo + fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{ + [RNFirebaseMessaging didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler]; +} +``` diff --git a/docs/api/analytics.md b/docs/modules/analytics.md similarity index 100% rename from docs/api/analytics.md rename to docs/modules/analytics.md diff --git a/docs/api/authentication.md b/docs/modules/authentication.md similarity index 100% rename from docs/api/authentication.md rename to docs/modules/authentication.md diff --git a/docs/api/cloud-messaging.md b/docs/modules/cloud-messaging.md similarity index 96% rename from docs/api/cloud-messaging.md rename to docs/modules/cloud-messaging.md index c467a43b..5b37ce41 100644 --- a/docs/api/cloud-messaging.md +++ b/docs/modules/cloud-messaging.md @@ -1,6 +1,6 @@ # Cloud Messaging -Firebase Cloud Messaging ([FCM](https://firebase.google.com/docs/cloud-messaging/)) allows you to send push messages at no +Firebase Cloud Messaging ([FCM](https://firebase.google.com/docs/cloud-messaging/)) allows you to send push messages at no cost to both Android & iOS platforms. Assuming the installation instructions have been followed, FCM is ready to go. As the Firebase Web SDK has limited messaging functionality, the following methods within `react-native-firebase` have been @@ -26,7 +26,7 @@ firebase.messaging().unsubscribeFromTopic('foobar'); ### getInitialNotification(): `Promise` -When the application has been opened from a notification `getInitialNotification` is called and the notification payload +When the application has been opened from a notification `getInitialNotification` is called and the notification payload is returned. Use `onMessage` for notifications when the app is running. ```javascript diff --git a/docs/api/crash.md b/docs/modules/crash.md similarity index 95% rename from docs/api/crash.md rename to docs/modules/crash.md index 2e1295b0..2e986a62 100644 --- a/docs/api/crash.md +++ b/docs/modules/crash.md @@ -4,7 +4,7 @@ RNFirebase provides crash reporting for your app out of the box. Please note cra ## Manual Crash Reporting -If you want to manually report a crash, such as a pre-caught exception this is possible by using the `report` method. +If you want to manually report a crash, such as a pre-caught exception this is possible by using the `report` method. ```javascript try { diff --git a/docs/api/database.md b/docs/modules/database.md similarity index 96% rename from docs/api/database.md rename to docs/modules/database.md index 465526b1..4cb0a302 100644 --- a/docs/api/database.md +++ b/docs/modules/database.md @@ -72,7 +72,7 @@ class MyComponent extends Component { ### Reading data -Firstack allows the database instance to [persist on disk](https://firebase.google.com/docs/database/android/offline-capabilities) if enabled. +Firebase allows the database instance to [persist on disk](https://firebase.google.com/docs/database/android/offline-capabilities) if enabled. To enable database persistence, pass the configuration option `persistence` before calls are made: ```javascript @@ -181,7 +181,7 @@ class ToDos extends Component { #### Differences between `.on` & `.once` With persistence enabled, any calls to a ref with `.once` will always read the data from disk and not contact the server. -On behavious differently, by first checking for a connection and if none exists returns the persisted data. If it successfully connects +On behaves differently, by first checking for a connection and if none exists returns the persisted data. If it successfully connects to the server, the new data will be returned and the disk data will be updated. The database refs has a `keepSynced()` function to tell the RNFirebase library to keep the data at the `ref` in sync. diff --git a/docs/api/storage.md b/docs/modules/storage.md similarity index 97% rename from docs/api/storage.md rename to docs/modules/storage.md index e2d0ae64..6ea5922c 100644 --- a/docs/api/storage.md +++ b/docs/modules/storage.md @@ -3,8 +3,6 @@ RNFirebase mimics the [Web Firebase SDK Storage](https://firebase.google.com/docs/storage/web/start), whilst providing some iOS and Android specific functionality. -All Storage operations are accessed via `storage()`. - ## Uploading files ### Simple diff --git a/docs/modules/transactions.md b/docs/modules/transactions.md new file mode 100644 index 00000000..ee273c2d --- /dev/null +++ b/docs/modules/transactions.md @@ -0,0 +1,38 @@ +# Transactions + +!> Transactions is currently an experimental feature in RNFirebase. Whilst it does work there may still be some issues with it, especially around offline connectivity handling. Please report any issues in the usual manner. + + +?> For help on how to use firebase transactions please see the [Firebase Transaction Documentation](https://firebase.google.com/docs/reference/js/firebase.database.Reference#transaction). + +### Android Implementation + +The [android implementation](https://github.com/invertase/react-native-firebase/blob/master/android/src/main/java/io/invertase/firebase/database/RNFirebaseTransactionHandler.java) makes use of [Condition](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html) and [ReentrantLock](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html) locks to handle transactions across the React Native Bridge. + + +### iOS Implementation + +The [iOS implementation](https://github.com/invertase/react-native-firebase/blob/master/ios/RNFirebase/RNFirebaseDatabase.m#L279) makes use of GCD (Grand Central Dispatch) to handle transactions across the React Native Bridge without blocking the application thread. Check out [this](https://mikeash.com/pyblog/friday-qa-2011-10-14-whats-new-in-gcd.html) post for some 'light' reading about it. + +!> Transactions that receive no response from react native's JS thread within 30 seconds are automatically aborted - this value is currently not configurable - PR welcome. + + +## Example + +```javascript +const ref = firebase.database().ref('user/posts'); + +ref.transaction((posts) => { + return (posts || 0) + 1; +}, (error, committed, snapshot) => { + if (error) { + console.log('Something went wrong', error); + } else if (!committed) { + console.log('Aborted'); // Returning undefined will trigger this + } else { + console.log('User posts incremented by 1'); + } + + console.log('User posts is now: ', snapshot.val()); +}); +``` diff --git a/docs/sw.js b/docs/sw.js new file mode 100644 index 00000000..ab031ac1 --- /dev/null +++ b/docs/sw.js @@ -0,0 +1,75 @@ +const RUNTIME = 'docsify' +const HOSTNAME_WHITELIST = [ + self.location.hostname, + 'fonts.gstatic.com', + 'fonts.googleapis.com', + 'unpkg.com' +] + +// The Util Function to hack URLs of intercepted requests +const getFixedUrl = (req) => { + var now = Date.now() + var url = new URL(req.url) + + // 1. fixed http URL + // Just keep syncing with location.protocol + // fetch(httpURL) belongs to active mixed content. + // And fetch(httpRequest) is not supported yet. + url.protocol = self.location.protocol + + // 2. add query for caching-busting. + // Github Pages served with Cache-Control: max-age=600 + // max-age on mutable content is error-prone, with SW life of bugs can even extend. + // Until cache mode of Fetch API landed, we have to workaround cache-busting with query string. + // Cache-Control-Bug: https://bugs.chromium.org/p/chromium/issues/detail?id=453190 + if (url.hostname === self.location.hostname) { + url.search += (url.search ? '&' : '?') + 'cache-bust=' + now + } + return url.href +} + +/** + * @Lifecycle Activate + * New one activated when old isnt being used. + * + * waitUntil(): activating ====> activated + */ +self.addEventListener('activate', event => { + event.waitUntil(self.clients.claim()) +}) + +/** + * @Functional Fetch + * All network requests are being intercepted here. + * + * void respondWith(Promise r) + */ +self.addEventListener('fetch', event => { + // Skip some of cross-origin requests, like those for Google Analytics. + if (HOSTNAME_WHITELIST.indexOf(new URL(event.request.url).hostname) > -1) { + // Stale-while-revalidate + // similar to HTTP's stale-while-revalidate: https://www.mnot.net/blog/2007/12/12/stale + // Upgrade from Jake's to Surma's: https://gist.github.com/surma/eb441223daaedf880801ad80006389f1 + const cached = caches.match(event.request) + const fixedUrl = getFixedUrl(event.request) + const fetched = fetch(fixedUrl, { cache: 'no-store' }) + const fetchedCopy = fetched.then(resp => resp.clone()) + + // Call respondWith() with whatever we get first. + // If the fetch fails (e.g disconnected), wait for the cache. + // If there’s nothing in cache, wait for the fetch. + // If neither yields a response, return offline pages. + event.respondWith( + Promise.race([fetched.catch(_ => cached), cached]) + .then(resp => resp || fetched) + .catch(_ => { /* eat any errors */ }) + ) + + // Update the cache with the version we fetched (only for ok status) + event.waitUntil( + Promise.all([fetchedCopy, caches.open(RUNTIME)]) + .then(([response, cache]) => response.ok && cache.put(event.request, response)) + .catch(_ => { /* eat any errors */ }) + ) + } +}) diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 00000000..117ad9d7 --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,36 @@ +# Usage + +After creating a Firebase project and installing the library, we can use it in our project by importing the library in our JavaScript: + +```javascript +import RNFirebase from 'react-native-firebase' +``` + +We need to tell the Firebase library we want to _configure_ the project. RNFirebase provides a way to configure both the native and the JavaScript side of the project at the same time with a single command: + +```javascript +const firebase = RNFirebase.initializeApp({ + // config options +}); +``` + +## Configuration Options + +| option | type | Default Value | Description | +|----------------|----------|-------------------------|----------------------------------------| +| debug | bool | false | When set to true, RNFirebase will log messages to the console and fire `debug` events we can listen to in `js` | +| persistence | bool | false | When set to true, database persistence will be enabled. | + +For instance: + +```javascript +import RNFirebase from 'react-native-firebase'; + +const configurationOptions = { + debug: true +}; + +const firebase = RNFirebase.initializeApp(configurationOptions); + +export default firebase; +``` diff --git a/ios/Podfile b/ios/Podfile deleted file mode 100644 index 990b86df..00000000 --- a/ios/Podfile +++ /dev/null @@ -1,71 +0,0 @@ -source 'https://github.com/CocoaPods/Specs.git' -use_frameworks! -platform :ios, '8.0' - -def common_pods - # pod 'RNFirebase', :path => '../' - # pod 'React', :path => '../node_modules/react-native' - [ - 'Firebase', - 'Firebase/Core', - 'Firebase/Auth', - 'Firebase/Storage', - 'Firebase/Database', - 'Firebase/RemoteConfig', - 'Firebase/Messaging' - ].each do |lib| - pod lib - end -end - -def test_pods - pod 'Quick', '~> 0.8.0' - pod 'Nimble', '~> 3.0.0' -end - -def setup - post_install do |installer| - installer.pods_project.targets.each do |target| - target.build_configurations.each do |configuration| - # configuration.build_settings['EXPANDED_CODE_SIGN_IDENTITY'] = "" - # configuration.build_settings['CODE_SIGNING_REQUIRED'] = "YES" - # configuration.build_settings['CODE_SIGNING_ALLOWED'] = "YES" - - target.build_settings(configuration.name)['OTHER_LDFLAGS'] = '$(inherited)' - target.build_settings(configuration.name)['USER_HEADER_SEARCH_PATHS'] = "$(BUILT_PRODUCTS_DIR)" - target.build_settings(configuration.name)['LD_DYLIB_INSTALL_NAME'] = '@rpath/${EXECUTABLE_NAME}' - target.build_settings(configuration.name)['LD_RUNPATH_SEARCH_PATHS'] = '$(inherited) @rpath @loader_path/../Frameworks @executable_path/Frameworks' - - target.build_settings(configuration.name)['ONLY_ACTIVE_ARCH'] = 'NO' - target.build_settings(configuration.name)['HEADER_SEARCH_PATHS'] = [ - "$(inherited)", - "${PODS_ROOT}/Headers/**", - "$(SRCROOT)/../../React/**", - "$(SRCROOT)/../../react-native/React/**", - '$(RN_ROOT)/React/**', - '$(PODS_ROOT)/Headers' - ].join(' ') - target.build_settings(configuration.name)['FRAMEWORK_SEARCH_PATHS'] = [ - "$(inherited)", - '$(PODS_ROOT)/**', - '$(PODS_CONFIGURATION_BUILD_DIR)/**' - ].join(' ') - target.build_settings(configuration.name)['OTHER_LDFLAGS'] = "$(inherited)" - end - end - end -end - -# target 'RNFirebase' do -# common_pods -# project "RNFirebase.xcodeproj" -# setup -# end - -target 'RNFirebaseTests' do - use_frameworks! - common_pods - test_pods - pod 'React', :path => '../node_modules/react-native' - setup -end diff --git a/ios/Podfile.template b/ios/Podfile.template index 9e4bbc45..1dd4a8ee 100644 --- a/ios/Podfile.template +++ b/ios/Podfile.template @@ -8,3 +8,4 @@ pod 'Firebase/DynamicLinks' pod 'Firebase/Messaging' pod 'Firebase/RemoteConfig' pod 'Firebase/Storage' +pod 'RNFirebase', :path => '../node_modules/react-native-firebase' diff --git a/ios/RNFirebase/RNFirebaseDatabase.m b/ios/RNFirebase/RNFirebaseDatabase.m index 4220f8b7..462eb06f 100644 --- a/ios/RNFirebase/RNFirebaseDatabase.m +++ b/ios/RNFirebase/RNFirebaseDatabase.m @@ -5,64 +5,61 @@ @interface RNFirebaseDBReference : NSObject @property RCTEventEmitter *emitter; @property FIRDatabaseQuery *query; +@property NSNumber *refId; @property NSString *path; -@property NSString *modifiersString; @property NSMutableDictionary *listeners; -@property FIRDatabaseHandle childAddedHandler; -@property FIRDatabaseHandle childModifiedHandler; -@property FIRDatabaseHandle childRemovedHandler; -@property FIRDatabaseHandle childMovedHandler; -@property FIRDatabaseHandle childValueHandler; + (NSDictionary *) snapshotToDict:(FIRDataSnapshot *) snapshot; @end @implementation RNFirebaseDBReference + - (id) initWithPathAndModifiers:(RCTEventEmitter *) emitter database:(FIRDatabase *) database + refId:(NSNumber *) refId path:(NSString *) path modifiers:(NSArray *) modifiers - modifiersString:(NSString *) modifiersString { self = [super init]; if (self) { _emitter = emitter; + _refId = refId; _path = path; - _modifiersString = modifiersString; _query = [self buildQueryAtPathWithModifiers:database path:path modifiers:modifiers]; _listeners = [[NSMutableDictionary alloc] init]; } return self; } -- (void) addEventHandler:(NSString *) eventName +- (void) addEventHandler:(NSNumber *) listenerId + eventName:(NSString *) eventName { - if (![self isListeningTo:eventName]) { + if (![_listeners objectForKey:listenerId]) { id withBlock = ^(FIRDataSnapshot * _Nonnull snapshot) { NSDictionary *props = [RNFirebaseDBReference snapshotToDict:snapshot]; [self sendJSEvent:DATABASE_DATA_EVENT title:eventName props: @{ @"eventName": eventName, + @"refId": _refId, + @"listenerId": listenerId, @"path": _path, - @"modifiersString": _modifiersString, @"snapshot": props }]; }; id errorBlock = ^(NSError * _Nonnull error) { NSLog(@"Error onDBEvent: %@", [error debugDescription]); - [self unsetListeningOn:eventName]; + [self removeEventHandler:listenerId eventName:eventName]; [self getAndSendDatabaseError:error - path:_path - modifiersString:_modifiersString]; + listenerId:listenerId]; }; int eventType = [self eventTypeFromName:eventName]; FIRDatabaseHandle handle = [_query observeEventType:eventType withBlock:withBlock withCancelBlock:errorBlock]; - [self setEventHandler:handle forName:eventName]; + [_listeners setObject:@(handle) forKey:listenerId]; } else { - NSLog(@"Warning Trying to add duplicate listener for type: %@ with modifiers: %@ for path: %@", eventName, _modifiersString, _path); + NSLog(@"Warning Trying to add duplicate listener for refId: %@ listenerId: %@", _refId, listenerId); } } @@ -74,7 +71,7 @@ callback(@[[NSNull null], @{ @"eventName": @"value", @"path": _path, - @"modifiersString": _modifiersString, + @"refId": _refId, @"snapshot": props }]); } @@ -83,7 +80,7 @@ callback(@[@{ @"eventName": DATABASE_ERROR_EVENT, @"path": _path, - @"modifiers": _modifiersString, + @"refId": _refId, @"code": @([error code]), @"details": [error debugDescription], @"message": [error localizedDescription], @@ -92,44 +89,14 @@ }]; } -- (void) removeEventHandler:(NSString *) name +- (void) removeEventHandler:(NSNumber *) listenerId + eventName:(NSString *) eventName { - int eventType = [self eventTypeFromName:name]; - switch (eventType) { - case FIRDataEventTypeValue: - if (self.childValueHandler != nil) { - [_query removeObserverWithHandle:self.childValueHandler]; - self.childValueHandler = nil; - } - break; - case FIRDataEventTypeChildAdded: - if (self.childAddedHandler != nil) { - [_query removeObserverWithHandle:self.childAddedHandler]; - self.childAddedHandler = nil; - } - break; - case FIRDataEventTypeChildChanged: - if (self.childModifiedHandler != nil) { - [_query removeObserverWithHandle:self.childModifiedHandler]; - self.childModifiedHandler = nil; - } - break; - case FIRDataEventTypeChildRemoved: - if (self.childRemovedHandler != nil) { - [_query removeObserverWithHandle:self.childRemovedHandler]; - self.childRemovedHandler = nil; - } - break; - case FIRDataEventTypeChildMoved: - if (self.childMovedHandler != nil) { - [_query removeObserverWithHandle:self.childMovedHandler]; - self.childMovedHandler = nil; - } - break; - default: - break; + FIRDatabaseHandle handle = [[_listeners objectForKey:listenerId] integerValue]; + if (handle) { + [_listeners removeObjectForKey:listenerId]; + [_query removeObserverWithHandle:handle]; } - [self unsetListeningOn:name]; } + (NSDictionary *) snapshotToDict:(FIRDataSnapshot *) snapshot @@ -159,21 +126,19 @@ } - (NSDictionary *) getAndSendDatabaseError:(NSError *) error - path:(NSString *) path - modifiersString:(NSString *) modifiersString + listenerId:(NSNumber *) listenerId { NSDictionary *event = @{ @"eventName": DATABASE_ERROR_EVENT, - @"path": path, - @"modifiers": modifiersString, + @"path": _path, + @"refId": _refId, + @"listenerId": listenerId, @"code": @([error code]), @"details": [error debugDescription], @"message": [error localizedDescription], @"description": [error description] }; - - // [self sendJSEvent:DATABASE_ERROR_EVENT title:DATABASE_ERROR_EVENT props: event]; - + @try { [_emitter sendEventWithName:DATABASE_ERROR_EVENT body:event]; } @@ -181,7 +146,7 @@ NSLog(@"An error occurred in getAndSendDatabaseError: %@", [err debugDescription]); NSLog(@"Tried to send: %@ with %@", DATABASE_ERROR_EVENT, event); } - + return event; } @@ -194,70 +159,59 @@ } } - - (FIRDatabaseQuery *) buildQueryAtPathWithModifiers:(FIRDatabase*) database path:(NSString*) path modifiers:(NSArray *) modifiers { FIRDatabaseQuery *query = [[database reference] child:path]; - - for (NSString *str in modifiers) { - if ([str isEqualToString:@"orderByKey"]) { - query = [query queryOrderedByKey]; - } else if ([str isEqualToString:@"orderByPriority"]) { - query = [query queryOrderedByPriority]; - } else if ([str isEqualToString:@"orderByValue"]) { - query = [query queryOrderedByValue]; - } else if ([str containsString:@"orderByChild"]) { - NSArray *args = [str componentsSeparatedByString:@":"]; - NSString *key = args[1]; - query = [query queryOrderedByChild:key]; - } else if ([str containsString:@"limitToLast"]) { - NSArray *args = [str componentsSeparatedByString:@":"]; - NSString *key = args[1]; - NSUInteger limit = key.integerValue; - query = [query queryLimitedToLast:limit]; - } else if ([str containsString:@"limitToFirst"]) { - NSArray *args = [str componentsSeparatedByString:@":"]; - NSString *key = args[1]; - NSUInteger limit = key.integerValue; - query = [query queryLimitedToFirst:limit]; - } else if ([str containsString:@"equalTo"]) { - NSArray *args = [str componentsSeparatedByString:@":"]; - int size = (int)[args count];; - id value = [self getIdValue:args[1] type:args[2]]; - if (size > 3) { - NSString *key = args[3]; - query = [query queryEqualToValue:value - childKey:key]; - } else { - query = [query queryEqualToValue:value]; + + for (NSDictionary *modifier in modifiers) { + NSString *type = [modifier valueForKey:@"type"]; + NSString *name = [modifier valueForKey:@"name"]; + if ([type isEqualToString:@"orderBy"]) { + if ([name isEqualToString:@"orderByKey"]) { + query = [query queryOrderedByKey]; + } else if ([name isEqualToString:@"orderByPriority"]) { + query = [query queryOrderedByPriority]; + } else if ([name isEqualToString:@"orderByValue"]) { + query = [query queryOrderedByValue]; + } else if ([name isEqualToString:@"orderByChild"]) { + NSString *key = [modifier valueForKey:@"key"]; + query = [query queryOrderedByChild:key]; } - } else if ([str containsString:@"endAt"]) { - NSArray *args = [str componentsSeparatedByString:@":"]; - int size = (int)[args count];; - id value = [self getIdValue:args[1] type:args[2]]; - if (size > 3) { - NSString *key = args[3]; - query = [query queryEndingAtValue:value - childKey:key]; - } else { - query = [query queryEndingAtValue:value]; + } else if ([type isEqualToString:@"limit"]) { + int limit = [[modifier valueForKey:@"limit"] integerValue]; + if ([name isEqualToString:@"limitToLast"]) { + query = [query queryLimitedToLast:limit]; + } else if ([name isEqualToString:@"limitToFirst"]) { + query = [query queryLimitedToFirst:limit]; } - } else if ([str containsString:@"startAt"]) { - NSArray *args = [str componentsSeparatedByString:@":"]; - id value = [self getIdValue:args[1] type:args[2]]; - int size = (int)[args count];; - if (size > 3) { - NSString *key = args[3]; - query = [query queryStartingAtValue:value - childKey:key]; - } else { - query = [query queryStartingAtValue:value]; + } else if ([type isEqualToString:@"filter"]) { + NSString* valueType = [modifier valueForKey:@"valueType"]; + NSString* key = [modifier valueForKey:@"key"]; + id value = [self getIdValue:[modifier valueForKey:@"value"] type:valueType]; + if ([name isEqualToString:@"equalTo"]) { + if (key != nil) { + query = [query queryEqualToValue:value childKey:key]; + } else { + query = [query queryEqualToValue:value]; + } + } else if ([name isEqualToString:@"endAt"]) { + if (key != nil) { + query = [query queryEndingAtValue:value childKey:key]; + } else { + query = [query queryEndingAtValue:value]; + } + } else if ([name isEqualToString:@"startAt"]) { + if (key != nil) { + query = [query queryStartingAtValue:value childKey:key]; + } else { + query = [query queryStartingAtValue:value]; + } } } } - + return query; } @@ -273,62 +227,15 @@ } } -- (void) setEventHandler:(FIRDatabaseHandle) handle - forName:(NSString *) name -{ - int eventType = [self eventTypeFromName:name]; - switch (eventType) { - case FIRDataEventTypeValue: - self.childValueHandler = handle; - break; - case FIRDataEventTypeChildAdded: - self.childAddedHandler = handle; - break; - case FIRDataEventTypeChildChanged: - self.childModifiedHandler = handle; - break; - case FIRDataEventTypeChildRemoved: - self.childRemovedHandler = handle; - break; - case FIRDataEventTypeChildMoved: - self.childMovedHandler = handle; - break; - default: - break; - } - [self setListeningOn:name withHandle:handle]; -} - -- (void) setListeningOn:(NSString *) name - withHandle:(FIRDatabaseHandle) handle -{ - [_listeners setValue:@(handle) forKey:name]; -} - -- (void) unsetListeningOn:(NSString *) name -{ - [_listeners removeObjectForKey:name]; -} - -- (BOOL) isListeningTo:(NSString *) name -{ - return [_listeners valueForKey:name] != nil; -} - - (BOOL) hasListeners { return [[_listeners allKeys] count] > 0; } -- (NSArray *) listenerKeys -{ - return [_listeners allKeys]; -} - - (int) eventTypeFromName:(NSString *)name { int eventType = FIRDataEventTypeValue; - + if ([name isEqualToString:DATABASE_VALUE_EVENT]) { eventType = FIRDataEventTypeValue; } else if ([name isEqualToString:DATABASE_CHILD_ADDED_EVENT]) { @@ -343,24 +250,6 @@ return eventType; } -- (void) cleanup { - if (self.childValueHandler > 0) { - [self removeEventHandler:DATABASE_VALUE_EVENT]; - } - if (self.childAddedHandler > 0) { - [self removeEventHandler:DATABASE_CHILD_ADDED_EVENT]; - } - if (self.childModifiedHandler > 0) { - [self removeEventHandler:DATABASE_CHILD_MODIFIED_EVENT]; - } - if (self.childRemovedHandler > 0) { - [self removeEventHandler:DATABASE_CHILD_REMOVED_EVENT]; - } - if (self.childMovedHandler > 0) { - [self removeEventHandler:DATABASE_CHILD_MOVED_EVENT]; - } -} - @end @@ -393,27 +282,27 @@ RCT_EXPORT_METHOD(startTransaction:(NSString *) path identifier:(NSString *) ide dispatch_semaphore_t sema = dispatch_semaphore_create(0); [transactionState setObject:sema forKey:@"semaphore"]; FIRDatabaseReference *ref = [self getPathRef:path]; - + [ref runTransactionBlock:^FIRTransactionResult * _Nonnull(FIRMutableData * _Nonnull currentData) { dispatch_barrier_async(_transactionQueue, ^{ [_transactions setValue:transactionState forKey:identifier]; [self sendTransactionEvent:DATABASE_TRANSACTION_EVENT body:@{ @"id": identifier, @"type": @"update", @"value": currentData.value }]; }); - + // wait for the js event handler to call tryCommitTransaction // this wait occurs on the Firebase Worker Queue // so if the tryCommitTransaction fails to signal the semaphore // no further blocks will be executed by Firebase until the timeout expires dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC); BOOL timedout = dispatch_semaphore_wait(sema, delayTime) != 0; - + BOOL abort = [transactionState valueForKey:@"abort"] || timedout; id value = [transactionState valueForKey:@"value"]; - + dispatch_barrier_async(_transactionQueue, ^{ [_transactions removeObjectForKey:identifier]; }); - + if (abort) { return [FIRTransactionResult abort]; } else { @@ -442,34 +331,34 @@ RCT_EXPORT_METHOD(startTransaction:(NSString *) path identifier:(NSString *) ide RCT_EXPORT_METHOD(tryCommitTransaction:(NSString *) identifier withData:(NSDictionary *) data) { __block NSMutableDictionary *transactionState; - + dispatch_sync(_transactionQueue, ^{ transactionState = [_transactions objectForKey: identifier]; }); - + if (!transactionState) { NSLog(@"tryCommitTransaction for unknown ID %@", identifier); return; } - + dispatch_semaphore_t sema = [transactionState valueForKey:@"semaphore"]; - + BOOL abort = [[data valueForKey:@"abort"] boolValue]; - + if (abort) { [transactionState setValue:@true forKey:@"abort"]; } else { id newValue = [data valueForKey:@"value"]; [transactionState setValue:newValue forKey:@"value"]; } - + dispatch_semaphore_signal(sema); } RCT_EXPORT_METHOD(enablePersistence:(BOOL) enable callback:(RCTResponseSenderBlock) callback) { - + BOOL isEnabled = [FIRDatabase database].persistenceEnabled; if ( isEnabled != enable) { [FIRDatabase database].persistenceEnabled = enable; @@ -526,10 +415,10 @@ RCT_EXPORT_METHOD(push:(NSString *) path { FIRDatabaseReference *ref = [self getPathRef:path]; FIRDatabaseReference *newRef = [ref childByAutoId]; - + NSURL *url = [NSURL URLWithString:newRef.URL]; NSString *newPath = [url path]; - + if ([data count] > 0) { [newRef setValue:[data valueForKey:@"value"] withCompletionBlock:^(NSError * _Nullable error, FIRDatabaseReference * _Nonnull ref) { if (error != nil) { @@ -540,7 +429,7 @@ RCT_EXPORT_METHOD(push:(NSString *) path @"message": [error localizedDescription], @"description": [error description] }; - + callback(@[evt]); } else { callback(@[[NSNull null], @{ @@ -558,58 +447,50 @@ RCT_EXPORT_METHOD(push:(NSString *) path } - -RCT_EXPORT_METHOD(on:(NSString *) path - modifiersString:(NSString *) modifiersString +RCT_EXPORT_METHOD(on:(nonnull NSNumber *) refId + path:(NSString *) path modifiers:(NSArray *) modifiers + listenerId:(nonnull NSNumber *) listenerId name:(NSString *) eventName callback:(RCTResponseSenderBlock) callback) { - RNFirebaseDBReference *ref = [self getDBHandle:path modifiers:modifiers modifiersString:modifiersString]; - [ref addEventHandler:eventName]; + RNFirebaseDBReference *ref = [self getDBHandle:refId path:path modifiers:modifiers]; + [ref addEventHandler:listenerId eventName:eventName]; callback(@[[NSNull null], @{ @"status": @"success", + @"refId": refId, @"handle": path }]); } -RCT_EXPORT_METHOD(once:(NSString *) path - modifiersString:(NSString *) modifiersString +RCT_EXPORT_METHOD(once:(nonnull NSNumber *) refId + path:(NSString *) path modifiers:(NSArray *) modifiers - name:(NSString *) name - callback:(RCTResponseSenderBlock) callback) -{ - RNFirebaseDBReference *ref = [self getDBHandle:path modifiers:modifiers modifiersString:modifiersString]; - [ref addSingleEventHandler:callback]; -} - -RCT_EXPORT_METHOD(off:(NSString *)path - modifiersString:(NSString *) modifiersString eventName:(NSString *) eventName callback:(RCTResponseSenderBlock) callback) { - NSString *key = [self getDBListenerKey:path withModifiers:modifiersString]; - NSArray *listenerKeys; - RNFirebaseDBReference *ref = [_dbReferences objectForKey:key]; - if (ref == nil) { - listenerKeys = @[]; - } else { - if (eventName == nil || [eventName isEqualToString:@""]) { - [ref cleanup]; - [_dbReferences removeObjectForKey:key]; - } else { - [ref removeEventHandler:eventName]; + RNFirebaseDBReference *ref = [self getDBHandle:refId path:path modifiers:modifiers]; + [ref addSingleEventHandler:callback]; +} + +RCT_EXPORT_METHOD(off:(nonnull NSNumber *) refId + listeners:(NSArray *) listeners + callback:(RCTResponseSenderBlock) callback) +{ + RNFirebaseDBReference *ref = [_dbReferences objectForKey:refId]; + if (ref != nil) { + for (NSDictionary *listener in listeners) { + NSNumber *listenerId = [listener valueForKey:@"listenerId"]; + NSString *eventName = [listener valueForKey:@"eventName"]; + [ref removeEventHandler:listenerId eventName:eventName]; if (![ref hasListeners]) { - [_dbReferences removeObjectForKey:key]; + [_dbReferences removeObjectForKey:refId]; } } - listenerKeys = [ref listenerKeys]; } callback(@[[NSNull null], @{ - @"result": @"success", - @"handle": path, - @"modifiersString": modifiersString, - @"remainingListeners": listenerKeys, + @"status": @"success", + @"refId": refId, }]); } @@ -680,30 +561,23 @@ RCT_EXPORT_METHOD(goOnline) } } -- (RNFirebaseDBReference *) getDBHandle:(NSString *) path - modifiers:modifiers - modifiersString:modifiersString +- (RNFirebaseDBReference *) getDBHandle:(NSNumber *) refId + path:(NSString *) path + modifiers:(NSArray *) modifiers { - NSString *key = [self getDBListenerKey:path withModifiers:modifiersString]; - RNFirebaseDBReference *ref = [_dbReferences objectForKey:key]; - + RNFirebaseDBReference *ref = [_dbReferences objectForKey:refId]; + if (ref == nil) { ref = [[RNFirebaseDBReference alloc] initWithPathAndModifiers:self database:[FIRDatabase database] + refId:refId path:path - modifiers:modifiers - modifiersString:modifiersString]; - [_dbReferences setObject:ref forKey:key]; + modifiers:modifiers]; + [_dbReferences setObject:ref forKey:refId]; } return ref; } -- (NSString *) getDBListenerKey:(NSString *) path - withModifiers:(NSString *) modifiersString -{ - return [NSString stringWithFormat:@"%@ | %@", path, modifiersString, nil]; -} - // Not sure how to get away from this... yet - (NSArray *)supportedEvents { return @[DATABASE_DATA_EVENT, DATABASE_ERROR_EVENT, DATABASE_TRANSACTION_EVENT]; diff --git a/lib/firebase.js b/lib/firebase.js index b1863487..4abfc79d 100644 --- a/lib/firebase.js +++ b/lib/firebase.js @@ -35,8 +35,10 @@ export default class Firebase { _crash: ?Object; auth: Function; + crash: Function; storage: Function; database: Function; + analytics: Function; messaging: Function; eventHandlers: Object; @@ -79,6 +81,8 @@ export default class Firebase { this.storage = this._staticsOrInstance('storage', StorageStatics, Storage); this.database = this._staticsOrInstance('database', DatabaseStatics, Database); this.messaging = this._staticsOrInstance('messaging', MessagingStatics, Messaging); + this.analytics = this._staticsOrInstance('analytics', {}, Analytics); + this.crash = this._staticsOrInstance('crash', {}, Crash); // init auth to start listeners this.auth(); @@ -107,20 +111,6 @@ export default class Firebase { return instances[name]; } - analytics() { - if (!this._analytics) { - this._analytics = new Analytics(this); - } - return this._analytics; - } - - crash() { - if (!this._crash) { - this._crash = new Crash(this); - } - return this._crash; - } - get apps(): Array { return Object.keys(instances); } diff --git a/lib/flow.js b/lib/flow.js index ab295056..c731dc3b 100644 --- a/lib/flow.js +++ b/lib/flow.js @@ -15,6 +15,22 @@ declare type CredentialType = { secret: string }; +declare type DatabaseListener = { + listenerId: number; + eventName: string; + successCallback: Function; + failureCallback?: Function; +}; + +declare type DatabaseModifier = { + type: 'orderBy' | 'limit' | 'filter'; + name?: string; + key?: string; + limit?: number; + value?: any; + valueType?: string; +}; + declare type GoogleApiAvailabilityType = { status: number, isAvailable: boolean, diff --git a/lib/modules/database/index.js b/lib/modules/database/index.js index e5baf473..775774ff 100644 --- a/lib/modules/database/index.js +++ b/lib/modules/database/index.js @@ -19,9 +19,8 @@ const FirebaseDatabaseEvt = new NativeEventEmitter(FirebaseDatabase); export default class Database extends Base { constructor(firebase: Object, options: Object = {}) { super(firebase, options); - this.subscriptions = {}; + this.references = {}; this.serverTimeOffset = 0; - this.errorSubscriptions = {}; this.persistenceEnabled = false; this.namespace = 'firebase:database'; this.transaction = new TransactionHandler(firebase, this, FirebaseDatabaseEvt); @@ -68,20 +67,12 @@ export default class Database extends Base { * @param errorCb * @returns {*} */ - on(path: string, modifiersString: string, modifiers: Array, eventName: string, cb: () => void, errorCb: () => void) { - const handle = this._handle(path, modifiersString); - this.log.debug('adding on listener', handle); - - if (!this.subscriptions[handle]) this.subscriptions[handle] = {}; - if (!this.subscriptions[handle][eventName]) this.subscriptions[handle][eventName] = []; - this.subscriptions[handle][eventName].push(cb); - - if (errorCb) { - if (!this.errorSubscriptions[handle]) this.errorSubscriptions[handle] = []; - this.errorSubscriptions[handle].push(errorCb); - } - - return promisify('on', FirebaseDatabase)(path, modifiersString, modifiers, eventName); + on(ref: Reference, listener: DatabaseListener) { + const { refId, path, query } = ref; + const { listenerId, eventName } = listener; + this.log.debug('on() : ', ref.refId, listenerId, eventName); + this.references[refId] = ref; + return promisify('on', FirebaseDatabase)(refId, path, query.getModifiers(), listenerId, eventName); } /** @@ -92,49 +83,35 @@ export default class Database extends Base { * @param origCB * @returns {*} */ - off(path: string, modifiersString: string, eventName?: string, origCB?: () => void) { - const handle = this._handle(path, modifiersString); - this.log.debug('off() : ', handle, eventName); + off( + refId: number, + // $FlowFixMe + listeners: Array, + remainingListenersCount: number + ) { + this.log.debug('off() : ', refId, listeners); - if (!this.subscriptions[handle] || (eventName && !this.subscriptions[handle][eventName])) { - this.log.warn('off() called, but not currently listening at that location (bad path)', handle, eventName); - return Promise.resolve(); - } + // Delete the reference if there are no more listeners + if (remainingListenersCount === 0) delete this.references[refId]; - if (eventName && origCB) { - const i = this.subscriptions[handle][eventName].indexOf(origCB); + if (listeners.length === 0) return Promise.resolve(); - if (i === -1) { - this.log.warn('off() called, but the callback specified is not listening at that location (bad path)', handle, eventName); - return Promise.resolve(); - } - - this.subscriptions[handle][eventName].splice(i, 1); - if (this.subscriptions[handle][eventName].length > 0) return Promise.resolve(); - } else if (eventName) { - this.subscriptions[handle][eventName] = []; - } else { - this.subscriptions[handle] = {}; - } - this.errorSubscriptions[handle] = []; - return promisify('off', FirebaseDatabase)(path, modifiersString, eventName); + return promisify('off', FirebaseDatabase)(refId, listeners.map(listener => ({ + listenerId: listener.listenerId, + eventName: listener.eventName, + }))); } /** - * Removes all event handlers and their native subscriptions + * Removes all references and their native listeners * @returns {Promise.<*>} */ cleanup() { const promises = []; - Object.keys(this.subscriptions).forEach((handle) => { - Object.keys(this.subscriptions[handle]).forEach((eventName) => { - const separator = handle.indexOf('|'); - const path = handle.substring(0, separator); - const modifiersString = handle.substring(separator + 1); - promises.push(this.off(path, modifiersString, eventName)); - }); + Object.keys(this.references).forEach((refId) => { + const ref = this.references[refId]; + promises.push(this.off(Number(refId), Object.values(ref.listeners), 0)); }); - return Promise.all(promises); } @@ -169,18 +146,6 @@ export default class Database extends Base { return Promise.reject({ status: 'Already enabled' }); } - /** - * - * @param path - * @param modifiersString - * @returns {string} - * @private - */ - _handle(path: string = '', modifiersString: string = '') { - return `${path}|${modifiersString}`; - } - - /** * * @param event @@ -188,18 +153,14 @@ export default class Database extends Base { */ _handleDatabaseEvent(event: Object) { const body = event.body || {}; - const { path, modifiersString, eventName, snapshot } = body; - const handle = this._handle(path, modifiersString); - - this.log.debug('_handleDatabaseEvent: ', handle, eventName, snapshot && snapshot.key); - - if (this.subscriptions[handle] && this.subscriptions[handle][eventName]) { - this.subscriptions[handle][eventName].forEach((cb) => { - cb(new Snapshot(new Reference(this, path, modifiersString.split('|')), snapshot), body); - }); + const { refId, listenerId, path, eventName, snapshot } = body; + this.log.debug('_handleDatabaseEvent: ', refId, listenerId, path, eventName, snapshot && snapshot.key); + if (this.references[refId] && this.references[refId].listeners[listenerId]) { + const cb = this.references[refId].listeners[listenerId].successCallback; + cb(new Snapshot(this.references[refId], snapshot)); } else { - FirebaseDatabase.off(path, modifiersString, eventName, () => { - this.log.debug('_handleDatabaseEvent: No JS listener registered, removed native listener', handle, eventName); + FirebaseDatabase.off(refId, [{ listenerId, eventName }], () => { + this.log.debug('_handleDatabaseEvent: No JS listener registered, removed native listener', refId, listenerId, eventName); }); } } @@ -235,13 +196,15 @@ export default class Database extends Base { * @private */ _handleDatabaseError(error: Object = {}) { - const { path, modifiers } = error; - const handle = this._handle(path, modifiers); + const { refId, listenerId, path } = error; const firebaseError = this._toFirebaseError(error); - this.log.debug('_handleDatabaseError ->', handle, 'database_error', error); + this.log.debug('_handleDatabaseError ->', refId, listenerId, path, 'database_error', error); - if (this.errorSubscriptions[handle]) this.errorSubscriptions[handle].forEach(listener => listener(firebaseError)); + if (this.references[refId] && this.references[refId].listeners[listenerId]) { + const failureCb = this.references[refId].listeners[listenerId].failureCallback; + if (failureCb) failureCb(firebaseError); + } } } @@ -250,4 +213,3 @@ export const statics = { TIMESTAMP: FirebaseDatabase.serverValueTimestamp || { '.sv': 'timestamp' }, }, }; - diff --git a/lib/modules/database/query.js b/lib/modules/database/query.js index 9d99b98a..959a098d 100644 --- a/lib/modules/database/query.js +++ b/lib/modules/database/query.js @@ -9,47 +9,41 @@ import Reference from './reference.js'; * @class Query */ export default class Query extends ReferenceBase { - static ref: Reference; + modifiers: Array; - static modifiers: Array; - - ref: Reference; - - constructor(ref: Reference, path: string, existingModifiers?: Array) { + constructor(ref: Reference, path: string, existingModifiers?: Array) { super(ref.database, path); this.log.debug('creating Query ', path, existingModifiers); - this.ref = ref; this.modifiers = existingModifiers ? [...existingModifiers] : []; } - setOrderBy(name: string, key?: string) { - if (key) { - this.modifiers.push(`${name}:${key}`); - } else { - this.modifiers.push(name); - } + orderBy(name: string, key?: string) { + this.modifiers.push({ + type: 'orderBy', + name, + key, + }); } - setLimit(name: string, limit: number) { - this.modifiers.push(`${name}:${limit}`); + limit(name: string, limit: number) { + this.modifiers.push({ + type: 'limit', + name, + limit, + }); } - setFilter(name: string, value: any, key?:string) { - if (key) { - this.modifiers.push(`${name}:${value}:${typeof value}:${key}`); - } else { - this.modifiers.push(`${name}:${value}:${typeof value}`); - } + filter(name: string, value: any, key?:string) { + this.modifiers.push({ + type: 'filter', + name, + value, + valueType: typeof value, + key, + }); } - getModifiers(): Array { + getModifiers(): Array { return [...this.modifiers]; } - - getModifiersString(): string { - if (!this.modifiers || !Array.isArray(this.modifiers)) { - return ''; - } - return this.modifiers.join('|'); - } } diff --git a/lib/modules/database/reference.js b/lib/modules/database/reference.js index 0055ae59..67f88c2d 100644 --- a/lib/modules/database/reference.js +++ b/lib/modules/database/reference.js @@ -10,6 +10,8 @@ import { ReferenceBase } from './../base'; import { promisify, isFunction, isObject, tryJSONParse, tryJSONStringify, generatePushID } from './../../utils'; const FirebaseDatabase = NativeModules.RNFirebaseDatabase; +// Unique Reference ID for native events +let refId = 1; /** * @link https://firebase.google.com/docs/reference/js/firebase.database.Reference @@ -17,15 +19,19 @@ const FirebaseDatabase = NativeModules.RNFirebaseDatabase; */ export default class Reference extends ReferenceBase { + refId: number; + listeners: { [listenerId: number]: DatabaseListener }; database: FirebaseDatabase; query: Query; - constructor(database: FirebaseDatabase, path: string, existingModifiers?: Array) { + constructor(database: FirebaseDatabase, path: string, existingModifiers?: Array) { super(database.firebase, path); + this.refId = refId++; + this.listeners = {}; this.database = database; this.namespace = 'firebase:db:ref'; this.query = new Query(this, path, existingModifiers); - this.log.debug('Created new Reference', this.database._handle(path, existingModifiers)); + this.log.debug('Created new Reference', this.refId, this.path); } /** @@ -81,7 +87,6 @@ export default class Reference extends ReferenceBase { const path = this.path; const _value = this._serializeAnyType(value); - return promisify('push', FirebaseDatabase)(path, _value) .then(({ ref }) => { const newRef = new Reference(this.database, ref); @@ -95,36 +100,37 @@ export default class Reference extends ReferenceBase { /** * - * @param eventType + * @param eventName * @param successCallback * @param failureCallback * @param context TODO * @returns {*} */ - on(eventType: string, successCallback: () => any, failureCallback: () => any) { + on(eventName: string, successCallback: () => any, failureCallback: () => any) { if (!isFunction(successCallback)) throw new Error('The specified callback must be a function'); if (failureCallback && !isFunction(failureCallback)) throw new Error('The specified error callback must be a function'); - const path = this.path; - const modifiers = this.query.getModifiers(); - const modifiersString = this.query.getModifiersString(); - this.log.debug('adding reference.on', path, modifiersString, eventType); - this.database.on(path, modifiersString, modifiers, eventType, successCallback, failureCallback); + this.log.debug('adding reference.on', this.refId, eventName); + const listener = { + listenerId: Object.keys(this.listeners).length + 1, + eventName, + successCallback, + failureCallback, + }; + this.listeners[listener.listenerId] = listener; + this.database.on(this, listener); return successCallback; } /** * - * @param eventType + * @param eventName * @param successCallback * @param failureCallback * @param context TODO * @returns {Promise.} */ - once(eventType: string = 'value', successCallback: (snapshot: Object) => void, failureCallback: (error: Error) => void) { - const path = this.path; - const modifiers = this.query.getModifiers(); - const modifiersString = this.query.getModifiersString(); - return promisify('once', FirebaseDatabase)(path, modifiersString, modifiers, eventType) + once(eventName: string = 'value', successCallback: (snapshot: Object) => void, failureCallback: (error: FirebaseError) => void) { + return promisify('once', FirebaseDatabase)(this.refId, this.path, this.query.getModifiers(), eventName) .then(({ snapshot }) => new Snapshot(this, snapshot)) .then((snapshot) => { if (isFunction(successCallback)) successCallback(snapshot); @@ -139,15 +145,37 @@ export default class Reference extends ReferenceBase { /** * - * @param eventType + * @param eventName * @param origCB * @returns {*} */ - off(eventType?: string = '', origCB?: () => any) { - const path = this.path; - const modifiersString = this.query.getModifiersString(); - this.log.debug('ref.off(): ', path, modifiersString, eventType); - return this.database.off(path, modifiersString, eventType, origCB); + off(eventName?: string = '', origCB?: () => any) { + this.log.debug('ref.off(): ', this.refId, eventName); + // $FlowFixMe + const listeners: Array = Object.values(this.listeners); + let listenersToRemove; + if (eventName && origCB) { + listenersToRemove = listeners.filter((listener) => { + return listener.eventName === eventName && listener.successCallback === origCB; + }); + // Only remove a single listener as per the web spec + if (listenersToRemove.length > 1) listenersToRemove = [listenersToRemove[0]]; + } else if (eventName) { + listenersToRemove = listeners.filter((listener) => { + return listener.eventName === eventName; + }); + } else if (origCB) { + listenersToRemove = listeners.filter((listener) => { + return listener.successCallback === origCB; + }); + } else { + listenersToRemove = listeners; + } + // Remove the listeners from the reference to prevent memory leaks + listenersToRemove.forEach((listener) => { + delete this.listeners[listener.listenerId]; + }); + return this.database.off(this.refId, listenersToRemove, Object.keys(this.listeners).length); } /** @@ -157,7 +185,7 @@ export default class Reference extends ReferenceBase { * @param onComplete * @param applyLocally */ - transaction(transactionUpdate: Function, onComplete, applyLocally: boolean = false) { + transaction(transactionUpdate: Function, onComplete: (?Error, boolean, ?Snapshot) => *, applyLocally: boolean = false) { if (!isFunction(transactionUpdate)) return Promise.reject(new Error('Missing transactionUpdate function argument.')); return new Promise((resolve, reject) => { @@ -227,7 +255,7 @@ export default class Reference extends ReferenceBase { */ orderBy(name: string, key?: string): Reference { const newRef = new Reference(this.database, this.path, this.query.getModifiers()); - newRef.query.setOrderBy(name, key); + newRef.query.orderBy(name, key); return newRef; } @@ -261,7 +289,7 @@ export default class Reference extends ReferenceBase { */ limit(name: string, limit: number): Reference { const newRef = new Reference(this.database, this.path, this.query.getModifiers()); - newRef.query.setLimit(name, limit); + newRef.query.limit(name, limit); return newRef; } @@ -308,7 +336,7 @@ export default class Reference extends ReferenceBase { */ filter(name: string, value: any, key?: string): Reference { const newRef = new Reference(this.database, this.path, this.query.getModifiers()); - newRef.query.setFilter(name, value, key); + newRef.query.filter(name, value, key); return newRef; } @@ -337,6 +365,17 @@ export default class Reference extends ReferenceBase { return this.path; } + /** + * Returns whether another Reference represent the same location and are from the + * same instance of firebase.app.App - multiple firebase apps not currently supported. + * @param {Reference} otherRef - Other reference to compare to this one + * @return {Boolean} Whether otherReference is equal to this one + * {@link https://firebase.google.com/docs/reference/js/firebase.database.Reference#isEqual} + */ + isEqual(otherRef: Reference): boolean { + return !!otherRef && otherRef.constructor === Reference && otherRef.key === this.key; + } + /** * GETTERS */ @@ -350,6 +389,14 @@ export default class Reference extends ReferenceBase { return new Reference(this.database, this.path.substring(0, this.path.lastIndexOf('/'))); } + /** + * A reference to itself + * @type {!Reference} + * {@link https://firebase.google.com/docs/reference/js/firebase.database.Reference#ref} + */ + get ref(): Reference { + return this; + } /** * Returns a ref to the root of db - '/' diff --git a/lib/modules/storage/reference.js b/lib/modules/storage/reference.js index b8cd4a34..04478d4f 100644 --- a/lib/modules/storage/reference.js +++ b/lib/modules/storage/reference.js @@ -80,7 +80,7 @@ export default class StorageReference extends ReferenceBase { * Alias to putFile * @returns {StorageReference.putFile} */ - get put() { + get put(): Function { return this.putFile; } diff --git a/lib/modules/storage/task.js b/lib/modules/storage/task.js index 4c8cb638..3b2ced7d 100644 --- a/lib/modules/storage/task.js +++ b/lib/modules/storage/task.js @@ -11,11 +11,13 @@ declare type UploadTaskSnapshotType = { downloadURL: string|null, metadata: Object, // TODO flow type def for https://firebase.google.com/docs/reference/js/firebase.storage.FullMetadata.html ref: StorageReference, - state: StorageStatics.TaskState.RUNNING - |StorageStatics.TaskState.PAUSED - |StorageStatics.TaskState.SUCCESS - |StorageStatics.TaskState.CANCELLED - |StorageStatics.TaskState.ERROR, + state: ( + typeof StorageStatics.TaskState.RUNNING + | typeof StorageStatics.TaskState.PAUSED + | typeof StorageStatics.TaskState.SUCCESS + | typeof StorageStatics.TaskState.CANCELLED + | typeof StorageStatics.TaskState.ERROR + ), task: StorageTask, totalBytes: number, }; @@ -24,15 +26,26 @@ declare type FuncSnapshotType = null|(snapshot: UploadTaskSnapshotType) => any; declare type FuncErrorType = null|(error: Error) => any; -declare type NextOrObserverType = null - |{ next?: FuncSnapshotType, error?: FuncErrorType, complete?:FuncSnapshotType } - |FuncSnapshotType; +declare type NextOrObserverType = null | + { + next?: FuncSnapshotType, + error?: FuncErrorType, + complete?:FuncSnapshotType + } | + FuncSnapshotType; /** * @url https://firebase.google.com/docs/reference/js/firebase.storage.UploadTask */ export default class StorageTask { - constructor(type: UPLOAD_TASK|DOWNLOAD_TASK, promise: Promise, storageRef: StorageReference) { + type: typeof UPLOAD_TASK | typeof DOWNLOAD_TASK + ref: StorageReference + storage: StorageReference.storage + path: StorageReference.path + then: Promise<*> + catch: () => Promise<*> + + constructor(type: typeof UPLOAD_TASK | typeof DOWNLOAD_TASK, promise: Promise<*>, storageRef: StorageReference) { this.type = type; this.ref = storageRef; this.storage = storageRef.storage; @@ -49,13 +62,13 @@ export default class StorageTask { * @returns {Promise.} * @private */ - _interceptSnapshotEvent(f: Function|null|undefined): null|() => any { + _interceptSnapshotEvent(f: ?Function): null | () => * { if (!isFunction(f)) return null; return (snapshot) => { const _snapshot = Object.assign({}, snapshot); _snapshot.task = this; _snapshot.ref = this.ref; - return f(_snapshot); + return f && f(_snapshot); }; } @@ -65,12 +78,13 @@ export default class StorageTask { * @returns {*} * @private */ - _interceptErrorEvent(f: Function|null|undefined): null|() => any { + _interceptErrorEvent(f: ?Function): null | (Error) => * { if (!isFunction(f)) return null; return (error) => { const _error = new Error(error.message); + // $FlowFixMe _error.code = error.code; - return f(_error); + return f && f(_error); }; } @@ -83,15 +97,41 @@ export default class StorageTask { * @private */ _subscribe(nextOrObserver: NextOrObserverType, error: FuncErrorType, complete: FuncSnapshotType): Function { - const observer = isObject(nextOrObserver); + let _error; + let _next; + let _complete; - const _error = this._interceptErrorEvent(observer ? nextOrObserver.error : error); - const _next = this._interceptSnapshotEvent(observer ? nextOrObserver.next : nextOrObserver); - const _complete = this._interceptSnapshotEvent(observer ? nextOrObserver.complete : complete); + if (typeof nextOrObserver === 'function') { + _error = this._interceptErrorEvent(error); + _next = this._interceptSnapshotEvent(nextOrObserver); + _complete = this._interceptSnapshotEvent(complete); + } else if (nextOrObserver) { + _error = this._interceptErrorEvent(nextOrObserver.error); + _next = this._interceptSnapshotEvent(nextOrObserver.next); + _complete = this._interceptSnapshotEvent(nextOrObserver.complete); + } - if (_next) this.storage._addListener(this.path, StorageStatics.TaskEvent.STATE_CHANGED, _next); - if (_error) this.storage._addListener(this.path, `${this.type}_failure`, _error); - if (_complete) this.storage._addListener(this.path, `${this.type}_success`, _complete); + if (_next) { + this.storage._addListener( + this.path, + StorageStatics.TaskEvent.STATE_CHANGED, + _next + ); + } + if (_error) { + this.storage._addListener( + this.path, + `${this.type}_failure`, + _error + ); + } + if (_complete) { + this.storage._addListener( + this.path, + `${this.type}_success`, + _complete + ); + } return () => { if (_next) this.storage._removeListener(this.path, StorageStatics.TaskEvent.STATE_CHANGED, _next); diff --git a/package.json b/package.json index b5ad4acc..439ff35a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "react-native-firebase", - "version": "1.0.0-alpha12", + "version": "1.0.1", "author": "Invertase (http://invertase.io)", "description": "A react native firebase library supporting both android and ios native firebase SDK's", "main": "index", @@ -9,7 +9,12 @@ "dev": "npm run compile -- --watch", "lint": "eslint ./src", "publish_pages": "gh-pages -d public/", - "watchcpx": "echo 'See https://github.com/wix/wml for watching changes. \r\n'", + "tests-npm-install": "cd tests && npm install", + "tests-packager": "cd tests && npm run start", + "tests-watch-init": "wml add $(node --eval \"console.log(require('path').resolve('./lib'));\") $(node --eval \"console.log(require('path').resolve('./tests/firebase'));\")", + "tests-watch-start": "watchman watch $(node --eval \"console.log(require('path').resolve('./lib'));\") && wml start", + "tests-watch-stop": "watchman watch-del $(node --eval \"console.log(require('path').resolve('./lib'));\") && wml stop", + "tests-pod-install": "cd tests && npm run ios:pod:install", "flow": "flow" }, "repository": { @@ -72,7 +77,8 @@ "flow-bin": "^0.40.0", "react": "^15.3.0", "react-dom": "^15.3.0", - "react-native": "^0.42.0" + "react-native": "^0.42.0", + "wml": "0.0.82" }, "dependencies": { "bows": "^1.6.0", diff --git a/tests/.babelrc b/tests/.babelrc new file mode 100644 index 00000000..71d5ed66 --- /dev/null +++ b/tests/.babelrc @@ -0,0 +1,9 @@ +{ + "presets": [ + "react-native" + ], + "ignore": [ + "node_modules/diff/lib/**/*.js", + "node_modules/diff/node_modules/**/*.js" + ] +} diff --git a/tests/.buckconfig b/tests/.buckconfig new file mode 100644 index 00000000..934256cb --- /dev/null +++ b/tests/.buckconfig @@ -0,0 +1,6 @@ + +[android] + target = Google Inc.:Google APIs:23 + +[maven_repositories] + central = https://repo1.maven.org/maven2 diff --git a/tests/.editorconfig b/tests/.editorconfig new file mode 100644 index 00000000..0f099897 --- /dev/null +++ b/tests/.editorconfig @@ -0,0 +1,10 @@ +# editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/tests/.eslintrc b/tests/.eslintrc new file mode 100644 index 00000000..c9d71b91 --- /dev/null +++ b/tests/.eslintrc @@ -0,0 +1,40 @@ +{ + "extends": "airbnb", + "parser": "babel-eslint", + "ecmaFeatures": { + "jsx": true + }, + "plugins": [ + "flowtype" + ], + "env": { + "es6": true, + "jasmine": true + }, + "parserOptions": { + "ecmaFeatures": { + "experimentalObjectRestSpread": true + } + }, + "rules": { + "class-methods-use-this": 0, + "no-underscore-dangle": 0, + "no-use-before-define": 0, + "arrow-body-style": 0, + "import/prefer-default-export": 0, + "radix": 0, + "new-cap": 0, + "max-len": 0, + "no-continue": 0, + "no-console": 0, + "global-require": 0, + "import/extensions": 0, + "import/no-unresolved": 0, + "import/no-extraneous-dependencies": 0, + "react/jsx-filename-extension": 0 + }, + "globals": { + "__DEV__": true, + "window": true + } +} diff --git a/tests/.flowconfig b/tests/.flowconfig new file mode 100644 index 00000000..53b071ef --- /dev/null +++ b/tests/.flowconfig @@ -0,0 +1,47 @@ +[ignore] +; We fork some components by platform +.*/*[.]android.js + +; Ignore "BUCK" generated dirs +/\.buckd/ + +; Ignore unexpected extra "@providesModule" +.*/node_modules/.*/node_modules/fbjs/.* + +; Ignore duplicate module providers +; For RN Apps installed via npm, "Libraries" folder is inside +; "node_modules/react-native" but in the source repo it is in the root +.*/Libraries/react-native/React.js +.*/Libraries/react-native/ReactNative.js + +[include] + +[libs] +node_modules/react-native/Libraries/react-native/react-native-interface.js +node_modules/react-native/flow +flow/ + +[options] +emoji=true + +module.system=haste + +experimental.strict_type_args=true + +munge_underscores=true + +module.name_mapper='^~\/\(.*\)$' -> '/\1' + + +suppress_type=$FlowIssue +suppress_type=$FlowFixMe +suppress_type=$FixMe + +suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(3[0-8]\\|[1-2][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\) +suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(3[0-8]\\|1[0-9]\\|[1-2][0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+ +suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy + +unsafe.enable_getters_and_setters=true + +[version] +^0.38.0 diff --git a/tests/.gitattributes b/tests/.gitattributes new file mode 100644 index 00000000..d42ff183 --- /dev/null +++ b/tests/.gitattributes @@ -0,0 +1 @@ +*.pbxproj -text diff --git a/tests/.watchmanconfig b/tests/.watchmanconfig new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/tests/.watchmanconfig @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 00000000..1ff84a01 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,363 @@ +# react-native-firebase test suite + +An **iOS** and **Android** React Native app built to test [`react-native-firebase`](https://github.com/invertase/react-native-firebase). + +## Install + +1. Clone the test application + +```bash +git clone https://github.com/invertase/react-native-firebase.git +``` + +2. Install the dependencies listed in `package.json` + +```bash +cd react-native-firebase/tests/ && npm install +``` + +### iOS Installation + +3. Install the test application's CocoaPods. +* See [troubleshooting](#installing-podfiles) if this doesn't work for you. + +```bash +npm run ios:pod:install +``` + +4. Start the React Native packager + +```bash +npm run start +``` + +5. In another terminal window, install the app on your emulator: + +```bash +npm run ios:dev +``` + +### Android Installation + +6. Start your emulator through Android Studio: Tools > Android > AVD Manager + +> You will need a version of the Android emulator that has the Play Store installed (you should be able to find it on the emulator's home screen or on the list of apps). + +7. Start the React Native packager if you haven't already in the iOS instructions. + +```bash +npm run start +``` + +8. Run the test app on your Android emulator: + +```bash +npm run android:dev +``` + +## Documentation + +`react-native-firebase` aims to match the Firebase Web API wherever possible. As a result, the tests are largely derived from the [Firebase Web API documentation](https://firebase.google.com/docs/reference/js/). + + +## Tests + +Tests are bootstrapped and ran when the app is booted. The status of each test suite and individual test will update as and when a test has completed or errored. + +### Running tests + +Tests can be run by pressing the play button in the toolbar of the app. Test can be run individually, by suite, or all at once. + +![Test suite Android](/docs/assets/test-suite-screenshot-android.png?raw=true) + + +### Adding test + +To add tests to an existing test suite, you need to pass a function to `addTests`. + +#### Synchronous tests + +Synchronous tests are created by passing a function to `it`. The next test is run immediately after the last line is executed. + +```javascript +testSuite.addTests(({ describe, it }) => { + describe('synchronous test', () => { + + it('does something correctly', () => { + + }); + + }); +}); +``` + +#### Asynchronous tests + +Tests can be asynchronous if they return a promise. The test suite waits for the promise to resolve before executing the next test. + +```javascript +testSuite.addTests(({ describe, it }) => { + describe('async successful test', () => { + + it('does something correctly', () => { + return new Promise((resolve, reject) => { + // ... + resolve(); + }); + }); + + }); +}); +``` + +Asynchronous tests can also be created using the `async` function syntax: + +```javascript +testSuite.addTests(({ describe, it }) => { + describe('async successful test', () => { + + it('does something correctly', async () => { + // ... + + await somethingAsynchronous(); + }); + + }); +}); +``` + +> When rejecting, always ensure a valid [JavaScript Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) is provided. + +### Creating a new test suite + +A test suite groups together test categories under the same Firebase feature. e.g. *Realtime Database* tests. + +To add a new test suite: + +1. Create a new directory within `src/tests`. +2. Create an `index.js` file. + +In this file, you need to create an instance of `TestSuite` - see [TestSuite constructor](#testsuite-constructor). + +```javascript +import TestSuite from 'lib/TestSuite'; + +const MyNewSuite = new TestSuite('Realtime Database Storage', 'Upload/Download storage tests'); + +export default MyNewSuite; +``` + +3. `addTests` is then used as many times as is necessary to add tests to the test suite, accepting a function that defines one or more tests. +4. The test suite must then be imported into `src/tests/index.js` and added to `testSuiteInstances` in order for it to be included in the list of test suites available to run in the app. + +## TestSuite API + +### TestSuite Constructor + +The TestSuite constructor accepts 3 arguments: + +- **name**: String containing the name of the test suite. e.g. 'Realtime Storage' +- **description**: String containing description of the test suite +- **firebase**: This is the object exported from `src/firebase` and contains both the native and web firebase instances. + +```javascript +import firebase from '../firebase'; + +new TestSuite('Realtime Database Storage', 'firebase.database()', firebase); +``` + +### Test Definition + +#### describe() + +The `describe()` function takes 2 - 3 arguments: + +- **description**: String describing the context or target of all the tests defined in `testDefinitions` +- **options**: (Optional) object of options: + * **focus**: Boolean marking all the tests defined in `testDefinitions` (and any others marked as focused) as the only one(s) that should run + * **pending**: Boolean marking all the tests defined in `testDefinitions` as excluded from running in the test suite +- **testDefinitions**: Function that defines 1 or more tests by calling `it`, `xit` or `fit` + +```javascript +function testCategory({ describe }) { + + describe('a feature', () => { + it('does something synchronously', () => { + + }); + + }); +} + +export default testCategory; +``` + +`describe()` statements can be arbitrarily nested. + +#### context() + +`context()` is an alias for `describe()` provided as syntactical sugar. `xcontext()` and `fcontext()` work similar to `xdescribe()` and `fdescribe()`, respectively. + +#### it() + +The `it()` function takes 2 - 3 arguments: + +- **description**: String describing the test defined in `testDefinition` +- **options**: (Optional) object of options: + * **focus**: Boolean marking the test defined in `testDefinition` (and any others marked as focused) as the only one(s) that should run + * **pending**: Boolean marking the test defined in `testDefinition` as excluded from running in the test suite + * **timeout**: Time in milliseconds a test is allowed to execute before it's considered to have timed out. Default is 5000ms (5 seconds). +- **testDefinition**: Function that defines a test with one or more assertions. Can be a synchronous or asynchronous function. Functions that return a promise cause the test environment to wait for the promise to be resolved before proceding to the next test. + +```javascript +it('does something synchronously', () => { + +}); + +it('does something asynchronously', async () => { + +}); + +it('does something else asynchronously', () => { + return new Promise(/* ... */); +}); +``` + +`it()` statements can *not* be nested. + +#### xdescribe() & xit() + +##### Pending Tests + +You can mark all tests within a `describe` statement as pending by using the `xdescribe` function instead. The test will appear greyed out and will not be run as part of the test suite. + +You can mark a single test as pending by using `xit` as you would `it`. + +Tests should only be marked as pending temporarily, and should not normally be committed to the test suite unless they are fully implemented. + +#### fdescribe() & fit() + +##### Focused Tests + +You can mark all tests within a `describe` statement as focused by using the `fdescribe` function instead. Tests that are focused will be the only ones that appear and run in the test suite until all tests are removed from being focused. This is useful for running and working on a few tests at a time. + +You can mark a single test as focused by using `fit` as you would `it`. + +#### Test Assertions + +The assertion library Should.js is used in the tests. The complete list of available assertions is available in the [Should.js documentation](https://shouldjs.github.io). + +#### Lifecycle methods + +Four lifecycle methods are provided for each test context: + +- **before** - Run once, before the current test context executes +- **beforeEach** - Run before every test in the current test context +- **after** - Run once, after the current test context has finished executing +- **afterEach** - Run after every test in the current test context + +A new test context is created when the test suite encounters any of `describe`, `xdescribe`, `fdescribe`, `context`, `xcontext` or `fcontext`, and close again when it reaches the end of the block. Test contexts can be nested and lifecycle hooks set for parent contexts apply for all descendents. + +Each lifecycle hook accepts either a synchronous function, a function that returns a promise or an `async` function. + +```javascript +function testCategory({ before, beforeEach, afterEach, after }) { + + before(() => console.log('Before all tests start.')); + beforeEach(() => console.log('Before every test starts.')); + + describe('sync successful test', function() { + // ... + }); + + afterEach(() => console.log('After each test starts.')); + after(() => console.log('After all tests are complete, with success or error.')); +} +``` + +An optional hash of options can also be passed as the first argument, defining one or more of the following values: + +* **timeout**: Time in milliseconds a hook is allowed to execute before it's considered to have timed out. Default is 5000ms (5 seconds). + +#### Accessing Firebase + +`react-native-firebase` is available `firebase.native`: + +```javascript +function testCategory({ describe, firebase }) { + + describe('sync successful test', 'category', function() { + firebase.native.database(); + }); +} +``` + +If you need to access the web API for Firebase to compare with the functionality of `react-native-firebase`, you can access it on `firebase.web`. + +> All tests should be written in terms of `react-native-firebase`'s behaviour and should **not** include direct comparisons with the web API. It's available for reference, only. + +## Development + +### Running test suite against latest version of react-native-firebase + +You can use the node module `wml` to automatically copy changes you make to `react-native-firebase` over to the test application so you can run the test suite against them. + +1. Install `wml` globally: + +```bash +npm install wml -g +``` + +2. Configure `wml` to copy changes from `react-native-firebase` to `react-native-firebase/tests/node_modules/react-native-firebase` is: + +```bash +wml add /full/path/to/react-native-firebase /full/path/to/react-native-firebase/tests/node_modules/react-native-firebase +``` + +3. Start `wml`: + +```bash +wml start +``` + +> JavaScript changes require restarting the React Native packager to take effect + +> Java changes will need to be rebuilt in Android Studio + +> Objective-C changes need to be rebuilt in Xcode + +4. Stop `wml` when you are finished: +```bash +wml stop +``` + +### Debugging or viewing internals of the test suite + +`react-native-firebase/tests` is compatible with [react-native-debugger](https://github.com/jhen0409/react-native-debugger) and is the recommended way to view the internal state of the test suite for development or troubleshooting. + +It allows you to view state and prop values of the React component tree, view the actions and contents of the Redux store and view and interact with the debugging console. + +Make sure **Remote JS Debugging** when running the application and close any chrome debugging windows that appear and start React Native Debugger. + +### Running the internal tests + +`react-native-firebase-tests` has its own tests to verify the testing framework is working as expected. These are run from the command line: + +```bash +npm run internal-tests +``` + +## Troubleshooting + +### Invalid React.podspec file: no implicit conversion of nil into String + +This error occurs if you are using ruby version 2.1.2. Upgrade your version of ruby and try again. + + +### Unable to resolve module ../../../node_modules/react-native/packager/... + +Run the packager separately, clearing the cache: + +```bash +npm start -- --reset-cache +``` diff --git a/tests/__tests__/src/hooks/asynchronousHooksTests.js b/tests/__tests__/src/hooks/asynchronousHooksTests.js new file mode 100644 index 00000000..0190eb86 --- /dev/null +++ b/tests/__tests__/src/hooks/asynchronousHooksTests.js @@ -0,0 +1,287 @@ +import 'should-sinon'; + +import TestSuite from '../lib/TestSuite'; + +function asynchronousHooksTests({ it: _it, describe: _describe }) { + _describe('before hooks:', () => { + _it('can return a promise that is resolved before executing other hooks and tests', async () => { + let valueBySecondHook = null; + let valueByTest = null; + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, before }) => { + let resolved = false; + + before(() => { + return new Promise((resolve) => { + setTimeout(() => { + resolved = true; + resolve(); + }, 500); + }); + }); + + before(() => { + valueBySecondHook = resolved; + }); + + it('', () => { + valueByTest = resolved; + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + valueBySecondHook.should.equal(true); + valueByTest.should.equal(true); + }); + + _it('can be an asynchronous function that is awaited before executing other hooks and tests', async () => { + let valueBySecondHook = null; + let valueByTest = null; + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, before }) => { + let resolved = false; + + before(async () => { + await new Promise((resolve) => { + setTimeout(() => { + resolved = true; + resolve(); + }, 500); + }); + }); + + before(() => { + valueBySecondHook = resolved; + }); + + it('', () => { + valueByTest = resolved; + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + valueBySecondHook.should.equal(true); + valueByTest.should.equal(true); + }); + }); + + _describe('beforeEach hooks:', () => { + _it('can return a promise that is resolved before executing other hooks and tests', async () => { + let valueBySecondHook = null; + let valueByTest = null; + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, beforeEach }) => { + let resolved = false; + + beforeEach(() => { + return new Promise((resolve) => { + setTimeout(() => { + resolved = true; + resolve(); + }, 500); + }); + }); + + beforeEach(() => { + valueBySecondHook = resolved; + }); + + it('', () => { + valueByTest = resolved; + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + valueBySecondHook.should.equal(true); + valueByTest.should.equal(true); + }); + + _it('can be an asynchronous function that is awaited before executing other hooks and tests', async () => { + let valueBySecondHook = null; + let valueByTest = null; + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, beforeEach }) => { + let resolved = false; + + beforeEach(async () => { + await new Promise((resolve) => { + setTimeout(() => { + resolved = true; + resolve(); + }, 500); + }); + }); + + beforeEach(() => { + valueBySecondHook = resolved; + }); + + it('', () => { + valueByTest = resolved; + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + valueBySecondHook.should.equal(true); + valueByTest.should.equal(true); + }); + }); + + _describe('afterEach hooks:', () => { + _it('can return a promise that is resolved before executing other hooks and tests', async () => { + let valueBySecondHook = null; + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, afterEach }) => { + let resolved = false; + + afterEach(() => { + return new Promise((resolve) => { + setTimeout(() => { + resolved = true; + resolve(); + }, 500); + }); + }); + + afterEach(() => { + valueBySecondHook = resolved; + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + valueBySecondHook.should.equal(true); + }); + + _it('can be an asynchronous function that is awaited before executing other hooks and tests', async () => { + let valueBySecondHook = null; + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, afterEach }) => { + let resolved = false; + + afterEach(async () => { + await new Promise((resolve) => { + setTimeout(() => { + resolved = true; + resolve(); + }, 500); + }); + }); + + afterEach(() => { + valueBySecondHook = resolved; + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + valueBySecondHook.should.equal(true); + }); + }); + + _describe('after hooks:', () => { + _it('can return a promise that is resolved before executing other hooks and tests', async () => { + let valueBySecondHook = null; + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, after }) => { + let resolved = false; + + after(() => { + return new Promise((resolve) => { + setTimeout(() => { + resolved = true; + resolve(); + }, 500); + }); + }); + + after(() => { + valueBySecondHook = resolved; + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + valueBySecondHook.should.equal(true); + }); + + _it('can be an asynchronous function that is awaited before executing other hooks and tests', async () => { + let valueBySecondHook = null; + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, after }) => { + let resolved = false; + + after(async () => { + await new Promise((resolve) => { + setTimeout(() => { + resolved = true; + resolve(); + }, 500); + }); + }); + + after(() => { + valueBySecondHook = resolved; + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + valueBySecondHook.should.equal(true); + }); + }); +} + +export default asynchronousHooksTests; diff --git a/tests/__tests__/src/hooks/failingHookTests.js b/tests/__tests__/src/hooks/failingHookTests.js new file mode 100644 index 00000000..57f104c7 --- /dev/null +++ b/tests/__tests__/src/hooks/failingHookTests.js @@ -0,0 +1,661 @@ +import 'should-sinon'; + +import TestSuite from '../lib/TestSuite'; + +function failingHookTests({ it: _it, describe: _describe }) { + _describe('before hooks:', () => { + _it('capture promise rejections and marks all tests as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, before }) => { + before(() => { + return new Promise((resolve, reject) => { + reject('failure'); + }); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('2 tests has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" before Hook: failure'); + }); + + _it('capture errors thrown in promises and marks all tests as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, before }) => { + before(() => { + return new Promise(() => { + true.should.equal(false); + }); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('2 tests has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" before Hook: AssertionError: expected true to be false'); + }); + + _it('captures errors thrown in asynchronous functions and marks all tests as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, before }) => { + before(async () => { + await new Promise(() => { + true.should.equal(false); + }); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('2 tests has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" before Hook: AssertionError: expected true to be false'); + }); + + _it('captures errors thrown in synchronous functions and marks all tests as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, before }) => { + before(() => { + true.should.equal(false); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('2 tests has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" before Hook: AssertionError: expected true to be false'); + }); + }); + + _describe('beforeEach hooks:', () => { + _it('capture promise rejections and marks test that follows as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + let testRuns = 0; + + testSuite.addTests(({ it, beforeEach }) => { + beforeEach(() => { + return new Promise((resolve, reject) => { + if (testRuns > 0) { + reject('failure'); + } else { + testRuns += 1; + resolve(); + } + }); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" beforeEach Hook: failure'); + }); + + _it('capture errors thrown in promises and marks test that follows as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + let testRuns = 0; + + testSuite.addTests(({ it, beforeEach }) => { + beforeEach(() => { + return new Promise((resolve) => { + if (testRuns > 0) { + true.should.equal(false); + } else { + testRuns += 1; + resolve(); + } + }); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" beforeEach Hook: AssertionError: expected true to be false'); + }); + + _it('captures errors thrown in asynchronous functions and marks test that follows as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + let testRuns = 0; + + testSuite.addTests(({ it, beforeEach }) => { + beforeEach(async () => { + await new Promise((resolve) => { + if (testRuns > 0) { + true.should.equal(false); + } else { + testRuns += 1; + resolve(); + } + }); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" beforeEach Hook: AssertionError: expected true to be false'); + }); + + _it('captures errors thrown in synchronous functions and marks test that follows as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + let testRuns = 0; + + testSuite.addTests(({ it, beforeEach }) => { + beforeEach(() => { + if (testRuns > 0) { + true.should.equal(false); + } else { + testRuns += 1; + } + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" beforeEach Hook: AssertionError: expected true to be false'); + }); + }); + + _describe('afterEach hooks:', () => { + _it('capture promise rejections and marks test that proceeded as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + let testRuns = 0; + + testSuite.addTests(({ it, afterEach }) => { + afterEach(() => { + return new Promise((resolve, reject) => { + if (testRuns > 0) { + reject('failure'); + } else { + testRuns += 1; + resolve(); + } + }); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" afterEach Hook: failure'); + }); + + _it('capture errors thrown in promises and marks test that proceeded as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + let testRuns = 0; + + testSuite.addTests(({ it, afterEach }) => { + afterEach(() => { + return new Promise((resolve) => { + if (testRuns > 0) { + true.should.equal(false); + } else { + testRuns += 1; + resolve(); + } + }); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" afterEach Hook: AssertionError: expected true to be false'); + }); + + _it('captures errors thrown in asynchronous functions and marks test that proceeded as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + let testRuns = 0; + + testSuite.addTests(({ it, afterEach }) => { + afterEach(async () => { + await new Promise((resolve) => { + if (testRuns > 0) { + true.should.equal(false); + } else { + testRuns += 1; + resolve(); + } + }); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" afterEach Hook: AssertionError: expected true to be false'); + }); + + _it('captures errors thrown in synchronous functions and marks test that proceeded as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + let testRuns = 0; + + testSuite.addTests(({ it, afterEach }) => { + afterEach(() => { + if (testRuns > 0) { + true.should.equal(false); + } else { + testRuns += 1; + } + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" afterEach Hook: AssertionError: expected true to be false'); + }); + }); + + _describe('after hooks:', () => { + _it('capture promise rejections and marks all tests as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, after }) => { + after(() => { + return new Promise((resolve, reject) => { + reject('failure'); + }); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('2 tests has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" after Hook: failure'); + }); + + _it('capture errors thrown in promises and marks all tests as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, after }) => { + after(() => { + return new Promise(() => { + true.should.equal(false); + }); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('2 tests has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" after Hook: AssertionError: expected true to be false'); + }); + + _it('captures errors thrown in asynchronous functions and marks all tests as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, after }) => { + after(async () => { + await new Promise(() => { + true.should.equal(false); + }); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('2 tests has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" after Hook: AssertionError: expected true to be false'); + }); + + _it('captures errors thrown in synchronous functions and marks all tests as failed', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, after }) => { + after(() => { + true.should.equal(false); + }); + + it('', () => { }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('2 tests has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" after Hook: AssertionError: expected true to be false'); + }); + }); +} + +export default failingHookTests; diff --git a/tests/__tests__/src/hooks/hookScopeTests.js b/tests/__tests__/src/hooks/hookScopeTests.js new file mode 100644 index 00000000..a809ccba --- /dev/null +++ b/tests/__tests__/src/hooks/hookScopeTests.js @@ -0,0 +1,278 @@ +import sinon from 'sinon'; +import 'should-sinon'; + +import TestSuite from '../lib/TestSuite'; + +function hookScopeTests({ it: _it, describe: _describe }) { + _describe('before hooks:', () => { + _it('apply only to the scope they are defined in and any child scopes', async () => { + const testSuite = new TestSuite('', '', {}); + + let value = 0; + let valueWhenOtherTestRuns = null; + let valueWhenSiblingTestRuns = null; + let valueWhenChildTestRuns = null; + + testSuite.addTests(({ it, before, context }) => { + context('', () => { + before(() => { + value = 1; + }); + + it('', () => { + valueWhenSiblingTestRuns = value; + }); + + context('', () => { + it('', () => { + valueWhenChildTestRuns = value; + }); + }); + }); + + it('', () => { + valueWhenOtherTestRuns = value; + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + valueWhenOtherTestRuns.should.equal(0); + valueWhenSiblingTestRuns.should.equal(1); + valueWhenChildTestRuns.should.equal(1); + }); + + _it('only run once for the scope they apply', async () => { + const testSuite = new TestSuite('', '', {}); + const beforeHook = sinon.spy(); + + testSuite.addTests(({ it, before, context }) => { + context('', () => { + before(beforeHook); + + it('', () => { }); + + context('', () => { + it('', () => { }); + }); + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + beforeHook.should.be.calledOnce(); + }); + }); + + _describe('beforeEach hooks:', () => { + _it('apply only to the scope they are defined in and any child scopes', async () => { + const testSuite = new TestSuite('', '', {}); + + let value = 0; + let valueWhenOtherTestRuns = null; + let valueWhenSiblingTestRuns = null; + let valueWhenChildTestRuns = null; + + testSuite.addTests(({ it, beforeEach, context }) => { + context('', () => { + beforeEach(() => { + value = 1; + }); + + it('', () => { + valueWhenSiblingTestRuns = value; + }); + + context('', () => { + it('', () => { + valueWhenChildTestRuns = value; + }); + }); + }); + + it('', () => { + valueWhenOtherTestRuns = value; + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + valueWhenOtherTestRuns.should.equal(0); + valueWhenSiblingTestRuns.should.equal(1); + valueWhenChildTestRuns.should.equal(1); + }); + + _it('are called once for every test in its scope', async () => { + const testSuite = new TestSuite('', '', {}); + const beforeEachHook = sinon.spy(); + + testSuite.addTests(({ it, beforeEach, context }) => { + context('', () => { + beforeEach(beforeEachHook); + + it('', () => { }); + + context('', () => { + it('', () => { }); + }); + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + beforeEachHook.should.be.calledTwice(); + }); + }); + + _describe('afterEach hooks:', () => { + _it('apply only to the scope they are defined in and any child scopes', async () => { + const testSuite = new TestSuite('', '', {}); + + let value = 0; + + testSuite.addTests(({ it, afterEach, context }) => { + context('', () => { + it('', () => { + value += 1; + }); + + context('', () => { + it('', () => { + value += 1; + }); + }); + + afterEach(() => { + value -= 1; + }); + }); + + it('', () => { + value += 1; + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + value.should.equal(1); + }); + + _it('are called once for every test in its scope', async () => { + const testSuite = new TestSuite('', '', {}); + const afterEachHook = sinon.spy(); + + testSuite.addTests(({ it, afterEach, context }) => { + context('', () => { + afterEach(afterEachHook); + + it('', () => { }); + + context('', () => { + it('', () => { }); + }); + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + afterEachHook.should.be.calledTwice(); + }); + }); + + _describe('after hooks:', () => { + _it('apply only to the scope they are defined in and any child scopes', async () => { + const testSuite = new TestSuite('', '', {}); + + let value = 0; + + testSuite.addTests(({ it, after, context }) => { + context('', () => { + it('', () => { + value += 1; + }); + + context('', () => { + it('', () => { + value += 1; + }); + }); + + after(() => { + value -= 1; + }); + }); + + it('', () => { + value += 1; + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + value.should.equal(2); + }); + + _it('are called once for every test in its scope', async () => { + const testSuite = new TestSuite('', '', {}); + const afterHook = sinon.spy(); + + testSuite.addTests(({ it, after, context }) => { + context('', () => { + it('', () => { }); + + context('', () => { + it('', () => { }); + }); + + after(afterHook); + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + afterHook.should.be.calledOnce(); + }); + }); +} + +export default hookScopeTests; diff --git a/tests/__tests__/src/hooks/hooksCallOrderTests.js b/tests/__tests__/src/hooks/hooksCallOrderTests.js new file mode 100644 index 00000000..0cfa94cd --- /dev/null +++ b/tests/__tests__/src/hooks/hooksCallOrderTests.js @@ -0,0 +1,310 @@ +import sinon from 'sinon'; +import 'should-sinon'; +import assert from 'assert'; + +import TestSuite from '../lib/TestSuite'; + +function hooksCallOrderTests({ it: _it, describe: _describe }) { + _describe('before hooks:', () => { + _it('calls before hooks defined in the same context in the order they are defined', async () => { + const testSuite = new TestSuite('', '', {}); + + const beforeCallbackA = sinon.spy(); + const beforeCallbackB = sinon.spy(); + + testSuite.addTests(({ it, before }) => { + before(beforeCallbackA); + before(beforeCallbackB); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + beforeCallbackA.should.have.been.called(); + beforeCallbackB.should.have.been.called(); + + assert(beforeCallbackB.calledAfter(beforeCallbackA)); + }); + + _it('calls before hooks defined in child contexts after those in parent contexts', async () => { + const testSuite = new TestSuite('', '', {}); + + const beforeCallbackA = sinon.spy(); + const beforeCallbackB = sinon.spy(); + + testSuite.addTests(({ it, before, context }) => { + before(beforeCallbackA); + + context('', () => { + before(beforeCallbackB); + + it('', () => { }); + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + beforeCallbackA.should.have.been.called(); + beforeCallbackB.should.have.been.called(); + + assert(beforeCallbackB.calledAfter(beforeCallbackA)); + }); + }); + + _describe('beforeEach hooks:', () => { + _it('calls beforeEach hooks defined in the same context in the order they are defined', async () => { + const testSuite = new TestSuite('', '', {}); + + const beforeEachCallbackA = sinon.spy(); + const beforeEachCallbackB = sinon.spy(); + + testSuite.addTests(({ it, beforeEach }) => { + beforeEach(beforeEachCallbackA); + beforeEach(beforeEachCallbackB); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + beforeEachCallbackA.should.have.been.called(); + beforeEachCallbackB.should.have.been.called(); + + assert(beforeEachCallbackB.calledAfter(beforeEachCallbackA)); + }); + + _it('calls beforeEach hooks defined in child contexts after those in parent contexts', async () => { + const testSuite = new TestSuite('', '', {}); + + const beforeEachCallbackA = sinon.spy(); + const beforeEachCallbackB = sinon.spy(); + + testSuite.addTests(({ it, beforeEach, context }) => { + beforeEach(beforeEachCallbackA); + + context('', () => { + beforeEach(beforeEachCallbackB); + + it('', () => { }); + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + beforeEachCallbackA.should.have.been.called(); + beforeEachCallbackB.should.have.been.called(); + + assert(beforeEachCallbackB.calledAfter(beforeEachCallbackA)); + }); + + _it('calls beforeEach hooks after before hooks', async () => { + const testSuite = new TestSuite('', '', {}); + + const beforeCallbackA = sinon.spy(); + const beforeEachCallbackB = sinon.spy(); + + testSuite.addTests(({ it, before, beforeEach }) => { + before(beforeCallbackA); + beforeEach(beforeEachCallbackB); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + beforeCallbackA.should.have.been.called(); + beforeEachCallbackB.should.have.been.called(); + + assert(beforeEachCallbackB.calledAfter(beforeCallbackA)); + }); + }); + + _describe('after hooks:', () => { + _it('calls after hooks defined in the same context in the order they are defined', async () => { + const testSuite = new TestSuite('', '', {}); + + const afterCallbackA = sinon.spy(); + const afterCallbackB = sinon.spy(); + + testSuite.addTests(({ it, after }) => { + after(afterCallbackA); + after(afterCallbackB); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + afterCallbackA.should.have.been.called(); + afterCallbackB.should.have.been.called(); + + assert(afterCallbackB.calledAfter(afterCallbackA)); + }); + + _it('calls after hooks defined in child contexts before those in parent contexts', async () => { + const testSuite = new TestSuite('', '', {}); + + const afterCallbackA = sinon.spy(); + const afterCallbackB = sinon.spy(); + + testSuite.addTests(({ it, after, context }) => { + after(afterCallbackA); + + context('', () => { + after(afterCallbackB); + + it('', () => { }); + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + afterCallbackA.should.have.been.called(); + afterCallbackB.should.have.been.called(); + + assert(afterCallbackA.calledAfter(afterCallbackB)); + }); + }); + + _describe('afterEach hooks:', () => { + _it('calls afterEach hooks defined in the same context in the order they are defined', async () => { + const testSuite = new TestSuite('', '', {}); + + const afterEachCallbackA = sinon.spy(); + const afterEachCallbackB = sinon.spy(); + + testSuite.addTests(({ it, afterEach }) => { + afterEach(afterEachCallbackA); + afterEach(afterEachCallbackB); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + afterEachCallbackA.should.have.been.called(); + afterEachCallbackB.should.have.been.called(); + + assert(afterEachCallbackB.calledAfter(afterEachCallbackA)); + }); + + _it('calls afterEach hooks defined in child contexts before those in parent contexts', async () => { + const testSuite = new TestSuite('', '', {}); + + const afterEachCallbackA = sinon.spy(); + const afterEachCallbackB = sinon.spy(); + + testSuite.addTests(({ it, afterEach, context }) => { + afterEach(afterEachCallbackA); + + context('', () => { + afterEach(afterEachCallbackB); + + it('', () => { }); + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + afterEachCallbackA.should.have.been.called(); + afterEachCallbackB.should.have.been.called(); + + assert(afterEachCallbackA.calledAfter(afterEachCallbackB)); + }); + + _it('calls afterEach hooks before after hooks', async () => { + const testSuite = new TestSuite('', '', {}); + + const afterCallbackA = sinon.spy(); + const afterEachCallbackB = sinon.spy(); + + testSuite.addTests(({ it, after, afterEach }) => { + after(afterCallbackA); + afterEach(afterEachCallbackB); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + afterCallbackA.should.have.been.called(); + afterEachCallbackB.should.have.been.called(); + + assert(afterCallbackA.calledAfter(afterEachCallbackB)); + }); + }); + + _describe('when there are no tests in a context or any of its children', () => { + _it('then doesn\'t call any hooks', async () => { + const testSuite = new TestSuite('', '', {}); + + const beforeCallback = sinon.spy(); + const beforeEachCallback = sinon.spy(); + const afterCallback = sinon.spy(); + const afterEachCallback = sinon.spy(); + + testSuite.addTests(({ before, beforeEach, after, afterEach, context }) => { + context('', () => { + before(beforeCallback); + beforeEach(beforeEachCallback); + afterEach(afterEachCallback); + after(afterCallback); + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + beforeCallback.should.not.have.been.called(); + beforeEachCallback.should.not.have.been.called(); + afterEachCallback.should.not.have.been.called(); + afterCallback.should.not.have.been.called(); + }); + }); +} + +export default hooksCallOrderTests; diff --git a/tests/__tests__/src/hooks/index.js b/tests/__tests__/src/hooks/index.js new file mode 100644 index 00000000..a444c6cb --- /dev/null +++ b/tests/__tests__/src/hooks/index.js @@ -0,0 +1,17 @@ +import TestSuite from '../lib/TestSuite'; + +import hooksCallOrderTest from './hooksCallOrderTests'; +import asynchronousHooksTests from './asynchronousHooksTests'; +import hookScopeTests from './hookScopeTests'; +import failingHookTests from './failingHookTests'; +import timingOutHookTests from './timingOutHookTests'; + +const suite = new TestSuite('Internal', 'Lifecycle methods', {}); + +suite.addTests(hooksCallOrderTest); +suite.addTests(asynchronousHooksTests); +suite.addTests(hookScopeTests); +suite.addTests(failingHookTests); +suite.addTests(timingOutHookTests); + +export default suite; diff --git a/tests/__tests__/src/hooks/timingOutHookTests.js b/tests/__tests__/src/hooks/timingOutHookTests.js new file mode 100644 index 00000000..3db70939 --- /dev/null +++ b/tests/__tests__/src/hooks/timingOutHookTests.js @@ -0,0 +1,327 @@ +import 'should-sinon'; + +import TestSuite from '../lib/TestSuite'; + +function failingHookTests({ it: _it, describe: _describe }) { + _describe('before hooks:', () => { + _it('timeout after 5 seconds by default', { timeout: 7000 }, async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, before }) => { + before(() => { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, 6000); + }); + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" before Hook: TimeoutError: before hook took longer than 5000ms. This can be extended with the timeout option.'); + }); + + _it('allows manually setting timeout', { timeout: 7000 }, async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, before }) => { + before({ timeout: 500 }, () => { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, 600); + }); + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" before Hook: TimeoutError: before hook took longer than 500ms. This can be extended with the timeout option.'); + }); + }); + + _describe('beforeEach hooks:', () => { + _it('timeout after 5 seconds by default', { timeout: 7000 }, async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, beforeEach }) => { + beforeEach(() => { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, 6000); + }); + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" beforeEach Hook: TimeoutError: beforeEach hook took longer than 5000ms. This can be extended with the timeout option.'); + }); + + _it('allows manually setting timeout', { timeout: 7000 }, async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, beforeEach }) => { + beforeEach({ timeout: 500 }, () => { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, 600); + }); + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" beforeEach Hook: TimeoutError: beforeEach hook took longer than 500ms. This can be extended with the timeout option.'); + }); + }); + + _describe('afterEach hooks:', () => { + _it('timeout after 5 seconds by default', { timeout: 7000 }, async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, afterEach }) => { + afterEach(() => { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, 6000); + }); + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" afterEach Hook: TimeoutError: afterEach hook took longer than 5000ms. This can be extended with the timeout option.'); + }); + + _it('allows manually setting timeout', { timeout: 7000 }, async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, afterEach }) => { + afterEach({ timeout: 500 }, () => { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, 600); + }); + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" afterEach Hook: TimeoutError: afterEach hook took longer than 500ms. This can be extended with the timeout option.'); + }); + }); + + _describe('after hooks:', () => { + _it('timeout after 5 seconds by default', { timeout: 7000 }, async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, after }) => { + after(() => { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, 6000); + }); + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" after Hook: TimeoutError: after hook took longer than 5000ms. This can be extended with the timeout option.'); + }); + + _it('allows manually setting timeout', { timeout: 7000 }, async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it, after }) => { + after({ timeout: 500 }, () => { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, 600); + }); + }); + + it('', () => { }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('Error occurred in "" after Hook: TimeoutError: after hook took longer than 500ms. This can be extended with the timeout option.'); + }); + }); +} + +export default failingHookTests; diff --git a/tests/__tests__/src/index.js b/tests/__tests__/src/index.js new file mode 100644 index 00000000..6e48e73e --- /dev/null +++ b/tests/__tests__/src/index.js @@ -0,0 +1,75 @@ +import 'babel-core/register'; +import 'babel-polyfill'; +import Promise from 'bluebird'; +import 'colors'; + +import RunStatus from './lib/RunStatus'; +import LifeCycleTestSuite from './hooks/index'; +import TestsTestSuite from './tests/index'; + +let successfulTests = 0; +let failingTests = 0; +const testErrors = {}; + +const suites = [ + LifeCycleTestSuite, + TestsTestSuite, +]; + +suites.forEach((suite) => { + suite.setStore({ + getState: () => { return {}; }, + }, (testSuiteAction) => { + if (testSuiteAction.message) { + console.error(testSuiteAction.message.red); + testErrors[suite.description] = { + message: testSuiteAction.message, + stackTrace: testSuiteAction.stackTrace, + }; + } + }, + (testAction) => { + const test = suite.testDefinitions.tests[testAction.testId]; + const testContext = suite.testDefinitions.testContexts[test.testContextId]; + + const description = (() => { + if (testContext.name && !test.description.startsWith(testContext.name)) { + return `${testContext.name} ${test.description}`; + } + + return test.description; + })(); + + if (testAction.status === RunStatus.OK) { + console.log(` ✅ ${description}`.green); + successfulTests += 1; + } else if (testAction.status === RunStatus.ERR) { + console.log(` ❌ ${description}`.red); + testErrors[test.description] = { + message: testAction.message, + stackTrace: testAction.stackTrace, + }; + failingTests += 1; + } + }); +}); + +Promise.each(suites, (suite) => { + console.log(`\n\n${suite.name} ${suite.description}:\n\r`); + return suite.run(); +}).then(() => { + console.log(`\n${successfulTests} tests passed.`); + + if (failingTests) { + console.log(`${failingTests} tests failed.`); + } + + if (Object.keys(testErrors).length > 0) { + console.log('\nErrors:'.red); + + Object.keys(testErrors).forEach((failingTestDescription) => { + const error = testErrors[failingTestDescription]; + console.error(`\n${failingTestDescription}: ${error.message} \n${error.stackTrace}`.red); + }); + } +}); diff --git a/tests/__tests__/src/tests/asynchronousTestTests.js b/tests/__tests__/src/tests/asynchronousTestTests.js new file mode 100644 index 00000000..1bda83a3 --- /dev/null +++ b/tests/__tests__/src/tests/asynchronousTestTests.js @@ -0,0 +1,82 @@ +import 'should-sinon'; + +import TestSuite from '../lib/TestSuite'; + +function asynchronousTestTests({ it: _it, describe: _describe }) { + _describe('tests', () => { + _it('can return a promise that is resolved before executing hooks and other tests', async () => { + let valueBySecondTest = null; + let valueByHook = null; + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, after }) => { + let resolved = false; + + it('', () => { + return new Promise((resolve) => { + setTimeout(() => { + resolved = true; + resolve(); + }, 500); + }); + }); + + it('', () => { + valueBySecondTest = resolved; + }); + + after(() => { + valueByHook = resolved; + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + valueBySecondTest.should.equal(true); + valueByHook.should.equal(true); + }); + + _it('can be an asynchronous function that is awaited before executing hooks and other tests', async () => { + let valueBySecondTest = null; + let valueByHook = null; + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, after }) => { + let resolved = false; + + it('', async () => { + await new Promise((resolve) => { + setTimeout(() => { + resolved = true; + resolve(); + }, 500); + }); + }); + + it('', () => { + valueBySecondTest = resolved; + }); + + after(() => { + valueByHook = resolved; + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(); + + valueBySecondTest.should.equal(true); + valueByHook.should.equal(true); + }); + }); + +} + +export default asynchronousTestTests; diff --git a/tests/__tests__/src/tests/failingTestTests.js b/tests/__tests__/src/tests/failingTestTests.js new file mode 100644 index 00000000..2345524a --- /dev/null +++ b/tests/__tests__/src/tests/failingTestTests.js @@ -0,0 +1,146 @@ +import 'should-sinon'; + +import TestSuite from '../lib/TestSuite'; + +function failingTestTests({ it: _it, describe: _describe }) { + _describe('running a test that is a function that returns a promise', () => { + _it('correctly reports a failure when the promise is rejected', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it }) => { + it('', () => { + return new Promise((resolve, reject) => { + reject('failure'); + }); + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('failure'); + }); + + _it('correctly reports a failure when an error is thrown', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it }) => { + + it('', () => { + return new Promise(() => { + false.should.equal(true); + }); + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('AssertionError: expected false to be true'); + }); + }); + + _describe('running an async function test', () => { + _it('correctly reports a failure when an error is thrown', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it }) => { + it('', async () => { + false.should.equal(true); + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('AssertionError: expected false to be true'); + }); + }); + + _describe('running an synchronous function test', () => { + _it('correctly reports a failure when an error is thrown', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it }) => { + it('', () => { + false.should.equal(true); + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('AssertionError: expected false to be true'); + }); + }); +} + +export default failingTestTests; diff --git a/tests/__tests__/src/tests/focusedTestTests.js b/tests/__tests__/src/tests/focusedTestTests.js new file mode 100644 index 00000000..8c756cd8 --- /dev/null +++ b/tests/__tests__/src/tests/focusedTestTests.js @@ -0,0 +1,84 @@ +import sinon from 'sinon'; +import 'should-sinon'; + +import TestSuite from '../lib/TestSuite'; + +function focusedTestTests({ it: _it, describe: _describe }) { + _describe('when fit is used instead of it', () => { + _it('a test is marked as focused', async () => { + const focusedTest = sinon.spy(); + const otherTest = sinon.spy(); + + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, fit }) => { + fit('', focusedTest); + + it('', otherTest); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(Object.keys(testSuite.testDefinitions.focusedTestIds)); + + focusedTest.should.be.called(); + otherTest.should.not.be.called(); + }); + }); + + _describe('when fdescribe is used instead of describe', () => { + _it('child tests are marked as focused', async () => { + const focusedTest = sinon.spy(); + const otherTest = sinon.spy(); + + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, fdescribe }) => { + fdescribe('', () => { + it('', focusedTest); + }); + + it('', otherTest); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(Object.keys(testSuite.testDefinitions.focusedTestIds)); + + focusedTest.should.be.called(); + otherTest.should.not.be.called(); + }); + }); + + _describe('when fcontext is used instead of context', () => { + _it('child tests are marked as focused', async () => { + const focusedTest = sinon.spy(); + const otherTest = sinon.spy(); + + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, fcontext }) => { + fcontext('', () => { + it('', focusedTest); + }); + + it('', otherTest); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + await testSuite.run(Object.keys(testSuite.testDefinitions.focusedTestIds)); + + focusedTest.should.be.called(); + otherTest.should.not.be.called(); + }); + }); +} + +export default focusedTestTests; diff --git a/tests/__tests__/src/tests/index.js b/tests/__tests__/src/tests/index.js new file mode 100644 index 00000000..c31f777d --- /dev/null +++ b/tests/__tests__/src/tests/index.js @@ -0,0 +1,17 @@ +import TestSuite from '../lib/TestSuite'; + +import asynchronousTestTests from './asynchronousTestTests'; +import focusedTestTests from './focusedTestTests'; +import pendingTestTests from './pendingTestTests'; +import failingTestTests from './failingTestTests'; +import timingOutTests from './timingOutTests'; + +const suite = new TestSuite('Internal', 'Test Definitions', {}); + +suite.addTests(asynchronousTestTests); +suite.addTests(focusedTestTests); +suite.addTests(pendingTestTests); +suite.addTests(failingTestTests); +suite.addTests(timingOutTests); + +export default suite; diff --git a/tests/__tests__/src/tests/pendingTestTests.js b/tests/__tests__/src/tests/pendingTestTests.js new file mode 100644 index 00000000..e7c128a9 --- /dev/null +++ b/tests/__tests__/src/tests/pendingTestTests.js @@ -0,0 +1,108 @@ +import sinon from 'sinon'; +import 'should-sinon'; + +import TestSuite from '../lib/TestSuite'; + +function pendingTestTests({ it: _it, describe: _describe }) { + _describe('when xit is used instead of it', () => { + _it('a test is marked as pending', async () => { + const pendingTest = sinon.spy(); + const otherTest = sinon.spy(); + + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, xit }) => { + xit('', pendingTest); + + it('', otherTest); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + const testIdsToRun = Object.keys(testSuite.testDefinitions.tests).reduce((memo, testId) => { + if (!testSuite.testDefinitions.pendingTestIds[testId]) { + memo.push(testId); + } + + return memo; + }, []); + + await testSuite.run(testIdsToRun); + + pendingTest.should.not.be.called(); + otherTest.should.be.called(); + }); + }); + + _describe('when xdescribe is used instead of describe', () => { + _it('child tests are marked as pending', async () => { + const pendingTest = sinon.spy(); + const otherTest = sinon.spy(); + + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, xdescribe }) => { + xdescribe('', () => { + it('', pendingTest); + }); + + it('', otherTest); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + const testIdsToRun = Object.keys(testSuite.testDefinitions.tests).reduce((memo, testId) => { + if (!testSuite.testDefinitions.pendingTestIds[testId]) { + memo.push(testId); + } + + return memo; + }, []); + + await testSuite.run(testIdsToRun); + + pendingTest.should.not.be.called(); + otherTest.should.be.called(); + }); + }); + + _describe('when xcontext is used instead of context', () => { + _it('child tests are marked as pending', async () => { + const pendingTest = sinon.spy(); + const otherTest = sinon.spy(); + + const testSuite = new TestSuite('', '', {}); + + testSuite.addTests(({ it, xcontext }) => { + xcontext('', () => { + it('', pendingTest); + }); + + it('', otherTest); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }); + + const testIdsToRun = Object.keys(testSuite.testDefinitions.tests).reduce((memo, testId) => { + if (!testSuite.testDefinitions.pendingTestIds[testId]) { + memo.push(testId); + } + + return memo; + }, []); + + await testSuite.run(testIdsToRun); + + pendingTest.should.not.be.called(); + otherTest.should.be.called(); + }); + }); +} + +export default pendingTestTests; diff --git a/tests/__tests__/src/tests/timingOutTests.js b/tests/__tests__/src/tests/timingOutTests.js new file mode 100644 index 00000000..88aac930 --- /dev/null +++ b/tests/__tests__/src/tests/timingOutTests.js @@ -0,0 +1,84 @@ + +import 'should-sinon'; + +import TestSuite from '../lib/TestSuite'; + +function timingOutTests({ it: _it, describe: _describe }) { + _describe('tests', () => { + _it('time out after 5 seconds by default', { timeout: 7000 }, async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it }) => { + it('', () => { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, 6000); + }); + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('TimeoutError: Test took longer than 5000ms. This can be extended with the timeout option.'); + }); + + _it('can set custom timeout', async () => { + const testSuite = new TestSuite('', '', {}); + const testSuiteStatuses = []; + const testStatuses = []; + + testSuite.addTests(({ it }) => { + it('', { timeout: 500 }, () => { + return new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, 1000); + }); + }); + }); + + testSuite.setStore({ + getState: () => { return {}; }, + }, (value) => { + testSuiteStatuses.push(value); + }, (value) => { + testStatuses.push(value); + }); + + await testSuite.run(); + + const lastTestSuiteStatus = testSuiteStatuses[testSuiteStatuses.length - 1]; + + lastTestSuiteStatus.progress.should.equal(100); + lastTestSuiteStatus.status.should.equal('error'); + lastTestSuiteStatus.message.should.equal('1 test has error(s).'); + + const lastTestStatus = testStatuses[testStatuses.length - 1]; + + lastTestStatus.status.should.equal('error'); + lastTestStatus.message.should.equal('TimeoutError: Test took longer than 500ms. This can be extended with the timeout option.'); + }); + }); +} + +export default timingOutTests; diff --git a/tests/android/app/BUCK b/tests/android/app/BUCK new file mode 100644 index 00000000..dbc66ee0 --- /dev/null +++ b/tests/android/app/BUCK @@ -0,0 +1,66 @@ +import re + +# To learn about Buck see [Docs](https://buckbuild.com/). +# To run your application with Buck: +# - install Buck +# - `npm start` - to start the packager +# - `cd android` +# - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"` +# - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck +# - `buck install -r android/app` - compile, install and run application +# + +lib_deps = [] +for jarfile in glob(['libs/*.jar']): + name = 'jars__' + re.sub(r'^.*/([^/]+)\.jar$', r'\1', jarfile) + lib_deps.append(':' + name) + prebuilt_jar( + name = name, + binary_jar = jarfile, + ) + +for aarfile in glob(['libs/*.aar']): + name = 'aars__' + re.sub(r'^.*/([^/]+)\.aar$', r'\1', aarfile) + lib_deps.append(':' + name) + android_prebuilt_aar( + name = name, + aar = aarfile, + ) + +android_library( + name = 'all-libs', + exported_deps = lib_deps +) + +android_library( + name = 'app-code', + srcs = glob([ + 'src/main/java/**/*.java', + ]), + deps = [ + ':all-libs', + ':build_config', + ':res', + ], +) + +android_build_config( + name = 'build_config', + package = 'com.reactnativefirebasedemo', +) + +android_resource( + name = 'res', + res = 'src/main/res', + package = 'com.reactnativefirebasedemo', +) + +android_binary( + name = 'app', + package_type = 'debug', + manifest = 'src/main/AndroidManifest.xml', + keystore = '//android/keystores:debug', + deps = [ + ':app-code', + ], +) diff --git a/tests/android/app/build.gradle b/tests/android/app/build.gradle new file mode 100644 index 00000000..f767d583 --- /dev/null +++ b/tests/android/app/build.gradle @@ -0,0 +1,144 @@ +apply plugin: "com.android.application" + +import com.android.build.OutputFile + +/** + * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets + * and bundleReleaseJsAndAssets). + * These basically call `react-native bundle` with the correct arguments during the Android build + * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the + * bundle directly from the development server. Below you can see all the possible configurations + * and their defaults. If you decide to add a configuration block, make sure to add it before the + * `apply from: "../../node_modules/react-native/react.gradle"` line. + * + * project.ext.react = [ + * // the name of the generated asset file containing your JS bundle + * bundleAssetName: "index.android.bundle", + * + * // the entry file for bundle generation + * entryFile: "index.android.js", + * + * // whether to bundle JS and assets in debug mode + * bundleInDebug: false, + * + * // whether to bundle JS and assets in release mode + * bundleInRelease: true, + * + * // whether to bundle JS and assets in another build variant (if configured). + * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants + * // The configuration property can be in the following formats + * // 'bundleIn${productFlavor}${buildType}' + * // 'bundleIn${buildType}' + * // bundleInFreeDebug: true, + * // bundleInPaidRelease: true, + * // bundleInBeta: true, + * + * // the root of your project, i.e. where "package.json" lives + * root: "../../", + * + * // where to put the JS bundle asset in debug mode + * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", + * + * // where to put the JS bundle asset in release mode + * jsBundleDirRelease: "$buildDir/intermediates/assets/release", + * + * // where to put drawable resources / React Native assets, e.g. the ones you use via + * // require('./image.png')), in debug mode + * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", + * + * // where to put drawable resources / React Native assets, e.g. the ones you use via + * // require('./image.png')), in release mode + * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", + * + * // by default the gradle tasks are skipped if none of the JS files or assets change; this means + * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to + * // date; if you have any other folders that you want to ignore for performance reasons (gradle + * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ + * // for example, you might want to remove it from here. + * inputExcludes: ["android/**", "ios/**"], + * + * // override which node gets called and with what additional arguments + * nodeExecutableAndArgs: ["node"] + * + * // supply additional arguments to the packager + * extraPackagerArgs: [] + * ] + */ + +apply from: "../../node_modules/react-native/react.gradle" +apply from: "../../node_modules/react-native-vector-icons/fonts.gradle" + +/** + * Set this to true to create two separate APKs instead of one: + * - An APK that only works on ARM devices + * - An APK that only works on x86 devices + * The advantage is the size of the APK is reduced by about 4MB. + * Upload all the APKs to the Play Store and people will download + * the correct one based on the CPU architecture of their device. + */ +def enableSeparateBuildPerCPUArchitecture = false + +/** + * Run Proguard to shrink the Java bytecode in release builds. + */ +def enableProguardInReleaseBuilds = false + +android { + compileSdkVersion 25 + buildToolsVersion '25.0.2' + + defaultConfig { + applicationId "com.reactnativefirebasedemo" + minSdkVersion 16 + targetSdkVersion 25 + versionCode 1 + versionName "1.0" + ndk { + abiFilters "armeabi-v7a", "x86" + } + } + splits { + abi { + reset() + enable enableSeparateBuildPerCPUArchitecture + universalApk false // If true, also generate a universal APK + include "armeabi-v7a", "x86" + } + } + buildTypes { + release { + minifyEnabled enableProguardInReleaseBuilds + proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" + } + } + // applicationVariants are e.g. debug, release + applicationVariants.all { variant -> + variant.outputs.each { output -> + // For each separate APK per architecture, set a unique version code as described here: + // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits + def versionCodes = ["armeabi-v7a": 1, "x86": 2] + def abi = output.getFilter(OutputFile.ABI) + if (abi != null) { // null for the universal-debug, universal-release variants + output.versionCodeOverride = + versionCodes.get(abi) * 1048576 + defaultConfig.versionCode + } + } + } +} + +dependencies { + compile project(':react-native-firebase') + compile project(':react-native-vector-icons') + compile fileTree(dir: "libs", include: ["*.jar"]) + compile "com.android.support:appcompat-v7:24.0.0" + compile "com.facebook.react:react-native:+" // From node_modules +} + +// Run this once to be able to run the application with BUCK +// puts all compile dependencies into folder libs for BUCK to use +task copyDownloadableDepsToLibs(type: Copy) { + from configurations.compile + into 'libs' +} + +apply plugin: 'com.google.gms.google-services' diff --git a/tests/android/app/google-services.json b/tests/android/app/google-services.json new file mode 100644 index 00000000..30a94c5d --- /dev/null +++ b/tests/android/app/google-services.json @@ -0,0 +1,42 @@ +{ + "project_info": { + "project_number": "305229645282", + "firebase_url": "https://rnfirebase-b9ad4.firebaseio.com", + "project_id": "rnfirebase-b9ad4", + "storage_bucket": "rnfirebase-b9ad4.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:305229645282:android:efe37851d57e1d05", + "android_client_info": { + "package_name": "com.reactnativefirebasedemo" + } + }, + "oauth_client": [ + { + "client_id": "305229645282-j8ij0jev9ut24odmlk9i215pas808ugn.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyCzbBYFyX8d6VdSu7T4s10IWYbPc-dguwM" + } + ], + "services": { + "analytics_service": { + "status": 1 + }, + "appinvite_service": { + "status": 1, + "other_platform_oauth_client": [] + }, + "ads_service": { + "status": 2 + } + } + } + ], + "configuration_version": "1" +} diff --git a/tests/android/app/proguard-rules.pro b/tests/android/app/proguard-rules.pro new file mode 100644 index 00000000..48361a90 --- /dev/null +++ b/tests/android/app/proguard-rules.pro @@ -0,0 +1,66 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Disabling obfuscation is useful if you collect stack traces from production crashes +# (unless you are using a system that supports de-obfuscate the stack traces). +-dontobfuscate + +# React Native + +# Keep our interfaces so they can be used by other ProGuard rules. +# See http://sourceforge.net/p/proguard/bugs/466/ +-keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip +-keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters +-keep,allowobfuscation @interface com.facebook.common.internal.DoNotStrip + +# Do not strip any method/class that is annotated with @DoNotStrip +-keep @com.facebook.proguard.annotations.DoNotStrip class * +-keep @com.facebook.common.internal.DoNotStrip class * +-keepclassmembers class * { + @com.facebook.proguard.annotations.DoNotStrip *; + @com.facebook.common.internal.DoNotStrip *; +} + +-keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * { + void set*(***); + *** get*(); +} + +-keep class * extends com.facebook.react.bridge.JavaScriptModule { *; } +-keep class * extends com.facebook.react.bridge.NativeModule { *; } +-keepclassmembers,includedescriptorclasses class * { native ; } +-keepclassmembers class * { @com.facebook.react.uimanager.UIProp ; } +-keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp ; } +-keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup ; } + +-dontwarn com.facebook.react.** + +# okhttp + +-keepattributes Signature +-keepattributes *Annotation* +-keep class okhttp3.** { *; } +-keep interface okhttp3.** { *; } +-dontwarn okhttp3.** + +# okio + +-keep class sun.misc.Unsafe { *; } +-dontwarn java.nio.file.* +-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement +-dontwarn okio.** diff --git a/tests/android/app/src/main/AndroidManifest.xml b/tests/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..c51b08ae --- /dev/null +++ b/tests/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/android/app/src/main/assets/fonts/Entypo.ttf b/tests/android/app/src/main/assets/fonts/Entypo.ttf new file mode 100644 index 00000000..1c8f5e91 Binary files /dev/null and b/tests/android/app/src/main/assets/fonts/Entypo.ttf differ diff --git a/tests/android/app/src/main/assets/fonts/EvilIcons.ttf b/tests/android/app/src/main/assets/fonts/EvilIcons.ttf new file mode 100644 index 00000000..b270f985 Binary files /dev/null and b/tests/android/app/src/main/assets/fonts/EvilIcons.ttf differ diff --git a/tests/android/app/src/main/assets/fonts/FontAwesome.ttf b/tests/android/app/src/main/assets/fonts/FontAwesome.ttf new file mode 100644 index 00000000..35acda2f Binary files /dev/null and b/tests/android/app/src/main/assets/fonts/FontAwesome.ttf differ diff --git a/tests/android/app/src/main/assets/fonts/Foundation.ttf b/tests/android/app/src/main/assets/fonts/Foundation.ttf new file mode 100644 index 00000000..6cce217d Binary files /dev/null and b/tests/android/app/src/main/assets/fonts/Foundation.ttf differ diff --git a/tests/android/app/src/main/assets/fonts/Ionicons.ttf b/tests/android/app/src/main/assets/fonts/Ionicons.ttf new file mode 100644 index 00000000..307ad889 Binary files /dev/null and b/tests/android/app/src/main/assets/fonts/Ionicons.ttf differ diff --git a/tests/android/app/src/main/assets/fonts/MaterialCommunityIcons.ttf b/tests/android/app/src/main/assets/fonts/MaterialCommunityIcons.ttf new file mode 100644 index 00000000..fb796951 Binary files /dev/null and b/tests/android/app/src/main/assets/fonts/MaterialCommunityIcons.ttf differ diff --git a/tests/android/app/src/main/assets/fonts/MaterialIcons.ttf b/tests/android/app/src/main/assets/fonts/MaterialIcons.ttf new file mode 100644 index 00000000..7015564a Binary files /dev/null and b/tests/android/app/src/main/assets/fonts/MaterialIcons.ttf differ diff --git a/tests/android/app/src/main/assets/fonts/Octicons.ttf b/tests/android/app/src/main/assets/fonts/Octicons.ttf new file mode 100644 index 00000000..5b1f7d6e Binary files /dev/null and b/tests/android/app/src/main/assets/fonts/Octicons.ttf differ diff --git a/tests/android/app/src/main/assets/fonts/SimpleLineIcons.ttf b/tests/android/app/src/main/assets/fonts/SimpleLineIcons.ttf new file mode 100644 index 00000000..6ecb6868 Binary files /dev/null and b/tests/android/app/src/main/assets/fonts/SimpleLineIcons.ttf differ diff --git a/tests/android/app/src/main/assets/fonts/Zocial.ttf b/tests/android/app/src/main/assets/fonts/Zocial.ttf new file mode 100644 index 00000000..e4ae46c6 Binary files /dev/null and b/tests/android/app/src/main/assets/fonts/Zocial.ttf differ diff --git a/tests/android/app/src/main/java/com/reactnativefirebasedemo/MainActivity.java b/tests/android/app/src/main/java/com/reactnativefirebasedemo/MainActivity.java new file mode 100644 index 00000000..fe7c5a28 --- /dev/null +++ b/tests/android/app/src/main/java/com/reactnativefirebasedemo/MainActivity.java @@ -0,0 +1,15 @@ +package com.reactnativefirebasedemo; + +import com.facebook.react.ReactActivity; + +public class MainActivity extends ReactActivity { + + /** + * Returns the name of the main component registered from JavaScript. + * This is used to schedule rendering of the component. + */ + @Override + protected String getMainComponentName() { + return "ReactNativeFirebaseDemo"; + } +} diff --git a/tests/android/app/src/main/java/com/reactnativefirebasedemo/MainApplication.java b/tests/android/app/src/main/java/com/reactnativefirebasedemo/MainApplication.java new file mode 100644 index 00000000..c6bc59dc --- /dev/null +++ b/tests/android/app/src/main/java/com/reactnativefirebasedemo/MainApplication.java @@ -0,0 +1,44 @@ +package com.reactnativefirebasedemo; + +import android.app.Application; + +import com.facebook.react.ReactApplication; +import io.invertase.firebase.RNFirebasePackage; +import com.oblador.vectoricons.VectorIconsPackage; +import com.facebook.react.ReactNativeHost; +import com.facebook.react.ReactPackage; +import com.facebook.react.shell.MainReactPackage; +import com.facebook.soloader.SoLoader; + +import java.util.Arrays; +import java.util.List; + +public class MainApplication extends Application implements ReactApplication { + + private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { + @Override + protected boolean getUseDeveloperSupport() { + return BuildConfig.DEBUG; + } + + @Override + protected List getPackages() { + return Arrays.asList( + new MainReactPackage(), + new VectorIconsPackage(), + new RNFirebasePackage() + ); + } + }; + + @Override + public ReactNativeHost getReactNativeHost() { + return mReactNativeHost; + } + + @Override + public void onCreate() { + super.onCreate(); + SoLoader.init(this, /* native exopackage */ false); + } +} diff --git a/tests/android/app/src/main/res/drawable-hdpi/ic_launcher.png b/tests/android/app/src/main/res/drawable-hdpi/ic_launcher.png new file mode 100755 index 00000000..7164396b Binary files /dev/null and b/tests/android/app/src/main/res/drawable-hdpi/ic_launcher.png differ diff --git a/tests/android/app/src/main/res/drawable-mdpi/ic_launcher.png b/tests/android/app/src/main/res/drawable-mdpi/ic_launcher.png new file mode 100755 index 00000000..fe1d9575 Binary files /dev/null and b/tests/android/app/src/main/res/drawable-mdpi/ic_launcher.png differ diff --git a/tests/android/app/src/main/res/drawable-xhdpi/ic_launcher.png b/tests/android/app/src/main/res/drawable-xhdpi/ic_launcher.png new file mode 100755 index 00000000..5e84bc0d Binary files /dev/null and b/tests/android/app/src/main/res/drawable-xhdpi/ic_launcher.png differ diff --git a/tests/android/app/src/main/res/drawable-xxhdpi/ic_launcher.png b/tests/android/app/src/main/res/drawable-xxhdpi/ic_launcher.png new file mode 100755 index 00000000..e0b2c4a0 Binary files /dev/null and b/tests/android/app/src/main/res/drawable-xxhdpi/ic_launcher.png differ diff --git a/tests/android/app/src/main/res/drawable-xxxhdpi/ic_launcher.png b/tests/android/app/src/main/res/drawable-xxxhdpi/ic_launcher.png new file mode 100755 index 00000000..e268634b Binary files /dev/null and b/tests/android/app/src/main/res/drawable-xxxhdpi/ic_launcher.png differ diff --git a/tests/android/app/src/main/res/values/strings.xml b/tests/android/app/src/main/res/values/strings.xml new file mode 100644 index 00000000..b322c107 --- /dev/null +++ b/tests/android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + ReactNativeFirebaseDemo + diff --git a/tests/android/app/src/main/res/values/styles.xml b/tests/android/app/src/main/res/values/styles.xml new file mode 100644 index 00000000..319eb0ca --- /dev/null +++ b/tests/android/app/src/main/res/values/styles.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/tests/android/build.gradle b/tests/android/build.gradle new file mode 100644 index 00000000..41f6c1d8 --- /dev/null +++ b/tests/android/build.gradle @@ -0,0 +1,48 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.3.0' + classpath 'com.google.gms:google-services:3.0.0' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + mavenLocal() + jcenter() + maven { + // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm + url "$rootDir/../node_modules/react-native/android" + } + } +} + +subprojects { + ext { + compileSdk = 25 + buildTools = "25.0.2" + minSdk = 16 + targetSdk = 25 + } + + afterEvaluate { project -> + if (!project.name.equalsIgnoreCase("app") + && project.hasProperty("android")) { + android { + compileSdkVersion compileSdk + buildToolsVersion buildTools + defaultConfig { + minSdkVersion minSdk + targetSdkVersion targetSdk + } + } + } + } +} diff --git a/tests/android/gradle.properties b/tests/android/gradle.properties new file mode 100644 index 00000000..1fd964e9 --- /dev/null +++ b/tests/android/gradle.properties @@ -0,0 +1,20 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx10248m -XX:MaxPermSize=256m +# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true + +android.useDeprecatedNdk=true diff --git a/tests/android/gradle/wrapper/gradle-wrapper.jar b/tests/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..13372aef Binary files /dev/null and b/tests/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/tests/android/gradle/wrapper/gradle-wrapper.properties b/tests/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..e6791164 --- /dev/null +++ b/tests/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Mar 07 13:10:12 GMT 2017 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip diff --git a/tests/android/gradlew b/tests/android/gradlew new file mode 100755 index 00000000..9d82f789 --- /dev/null +++ b/tests/android/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/tests/android/gradlew.bat b/tests/android/gradlew.bat new file mode 100644 index 00000000..aec99730 --- /dev/null +++ b/tests/android/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/tests/android/keystores/BUCK b/tests/android/keystores/BUCK new file mode 100644 index 00000000..15da20e6 --- /dev/null +++ b/tests/android/keystores/BUCK @@ -0,0 +1,8 @@ +keystore( + name = 'debug', + store = 'debug.keystore', + properties = 'debug.keystore.properties', + visibility = [ + 'PUBLIC', + ], +) diff --git a/tests/android/keystores/debug.keystore.properties b/tests/android/keystores/debug.keystore.properties new file mode 100644 index 00000000..121bfb49 --- /dev/null +++ b/tests/android/keystores/debug.keystore.properties @@ -0,0 +1,4 @@ +key.store=debug.keystore +key.alias=androiddebugkey +key.store.password=android +key.alias.password=android diff --git a/tests/android/settings.gradle b/tests/android/settings.gradle new file mode 100644 index 00000000..4ead5270 --- /dev/null +++ b/tests/android/settings.gradle @@ -0,0 +1,7 @@ +rootProject.name = 'ReactNativeFirebaseDemo' +include ':react-native-firebase' +project(':react-native-firebase').projectDir = new File(rootProject.projectDir, './../../android') +include ':react-native-vector-icons' +project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android') + +include ':app' diff --git a/tests/docs/assets/test-suite-screenshot-android.png b/tests/docs/assets/test-suite-screenshot-android.png new file mode 100644 index 00000000..a3a3f9dc Binary files /dev/null and b/tests/docs/assets/test-suite-screenshot-android.png differ diff --git a/tests/firebase/.gitkeep b/tests/firebase/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/tests/index.android.js b/tests/index.android.js new file mode 100644 index 00000000..9e8fc32c --- /dev/null +++ b/tests/index.android.js @@ -0,0 +1,5 @@ +import { AppRegistry } from 'react-native'; +import bootstrap from './src/main'; + + +AppRegistry.registerComponent('ReactNativeFirebaseDemo', () => bootstrap); diff --git a/tests/index.ios.js b/tests/index.ios.js new file mode 100644 index 00000000..597382bc --- /dev/null +++ b/tests/index.ios.js @@ -0,0 +1,4 @@ +import { AppRegistry } from 'react-native'; +import bootstrap from './src/main'; + +AppRegistry.registerComponent('ReactNativeFirebaseDemo', () => bootstrap); diff --git a/tests/ios/GoogleService-Info.plist b/tests/ios/GoogleService-Info.plist new file mode 100644 index 00000000..30da4b8d --- /dev/null +++ b/tests/ios/GoogleService-Info.plist @@ -0,0 +1,40 @@ + + + + + AD_UNIT_ID_FOR_BANNER_TEST + ca-app-pub-3940256099942544/2934735716 + AD_UNIT_ID_FOR_INTERSTITIAL_TEST + ca-app-pub-3940256099942544/4411468910 + CLIENT_ID + 305229645282-22imndi01abc2p6esgtu1i1m9mqrd0ib.apps.googleusercontent.com + REVERSED_CLIENT_ID + com.googleusercontent.apps.305229645282-22imndi01abc2p6esgtu1i1m9mqrd0ib + API_KEY + AIzaSyAcdVLG5dRzA1ck_fa_xd4Z0cY7cga7S5A + GCM_SENDER_ID + 305229645282 + PLIST_VERSION + 1 + BUNDLE_ID + com.invertase.ReactNativeFirebaseDemo + PROJECT_ID + rnfirebase-b9ad4 + STORAGE_BUCKET + rnfirebase-b9ad4.appspot.com + IS_ADS_ENABLED + + IS_ANALYTICS_ENABLED + + IS_APPINVITE_ENABLED + + IS_GCM_ENABLED + + IS_SIGNIN_ENABLED + + GOOGLE_APP_ID + 1:305229645282:ios:7b45748cb1117d2d + DATABASE_URL + https://rnfirebase-b9ad4.firebaseio.com + + \ No newline at end of file diff --git a/tests/ios/Podfile b/tests/ios/Podfile new file mode 100644 index 00000000..5331dc7e --- /dev/null +++ b/tests/ios/Podfile @@ -0,0 +1,41 @@ +install! 'cocoapods', :deterministic_uuids => false +# Uncomment this line to define a global platform for your project +# platform :ios, '9.0' + +target 'ReactNativeFirebaseDemo' do + platform :ios, '8.0' + # Uncomment this line if you're using Swift or would like to use dynamic frameworks + # use_frameworks! + + # Pods for ReactNativeFirebaseDemo + pod 'React', :path => '../node_modules/react-native', :subspecs => [ + 'Core', + 'RCTActionSheet', + 'RCTAnimation', + 'RCTCameraRoll', + 'RCTGeolocation', + 'RCTImage', + 'RCTLinkingIOS', + 'RCTNetwork', + 'RCTPushNotification', + 'RCTSettings', + 'RCTText', + 'RCTVibration', + 'RCTWebSocket' + # Add any other subspecs you want to use in your project + ] + + pod 'Firebase/Auth' + pod 'Firebase/Analytics' + pod 'Firebase/AppIndexing' + pod 'Firebase/Core' + pod 'Firebase/Crash' + pod 'Firebase/Database' + pod 'Firebase/DynamicLinks' + pod 'Firebase/Messaging' + pod 'Firebase/RemoteConfig' + pod 'Firebase/Storage' + + + pod 'RNFirebase', :path => './../../' +end diff --git a/tests/ios/Podfile.lock b/tests/ios/Podfile.lock new file mode 100644 index 00000000..c3bb0e75 --- /dev/null +++ b/tests/ios/Podfile.lock @@ -0,0 +1,168 @@ +PODS: + - Firebase/Analytics (3.14.0): + - Firebase/Core + - Firebase/AppIndexing (3.14.0): + - Firebase/Core + - FirebaseAppIndexing (= 1.2.0) + - Firebase/Auth (3.14.0): + - Firebase/Core + - FirebaseAuth (= 3.1.1) + - Firebase/Core (3.14.0): + - FirebaseAnalytics (= 3.7.0) + - FirebaseCore (= 3.5.1) + - Firebase/Crash (3.14.0): + - Firebase/Core + - FirebaseCrash (= 1.1.6) + - Firebase/Database (3.14.0): + - Firebase/Core + - FirebaseDatabase (= 3.1.2) + - Firebase/DynamicLinks (3.14.0): + - Firebase/Core + - FirebaseDynamicLinks (= 1.3.3) + - Firebase/Messaging (3.14.0): + - Firebase/Core + - FirebaseMessaging (= 1.2.2) + - Firebase/RemoteConfig (3.14.0): + - Firebase/Core + - FirebaseRemoteConfig (= 1.3.4) + - Firebase/Storage (3.14.0): + - Firebase/Core + - FirebaseStorage (= 1.1.0) + - FirebaseAnalytics (3.7.0): + - FirebaseCore (~> 3.5) + - FirebaseInstanceID (~> 1.0) + - GoogleToolboxForMac/NSData+zlib (~> 2.1) + - FirebaseAppIndexing (1.2.0) + - FirebaseAuth (3.1.1): + - FirebaseAnalytics (~> 3.7) + - GoogleToolboxForMac/NSDictionary+URLArguments (~> 2.1) + - GTMSessionFetcher/Core (~> 1.1) + - FirebaseCore (3.5.1): + - GoogleToolboxForMac/NSData+zlib (~> 2.1) + - FirebaseCrash (1.1.6): + - FirebaseAnalytics (~> 3.7) + - FirebaseInstanceID (~> 1.0) + - GoogleToolboxForMac/Logger (~> 2.1) + - GoogleToolboxForMac/NSData+zlib (~> 2.1) + - Protobuf (~> 3.1) + - FirebaseDatabase (3.1.2): + - FirebaseAnalytics (~> 3.7) + - FirebaseDynamicLinks (1.3.3): + - FirebaseAnalytics (~> 3.7) + - FirebaseInstanceID (1.0.9) + - FirebaseMessaging (1.2.2): + - FirebaseAnalytics (~> 3.7) + - FirebaseInstanceID (~> 1.0) + - GoogleToolboxForMac/Logger (~> 2.1) + - Protobuf (~> 3.1) + - FirebaseRemoteConfig (1.3.4): + - FirebaseAnalytics (~> 3.7) + - FirebaseInstanceID (~> 1.0) + - GoogleToolboxForMac/NSData+zlib (~> 2.1) + - Protobuf (~> 3.1) + - FirebaseStorage (1.1.0): + - FirebaseAnalytics (~> 3.7) + - GTMSessionFetcher/Core (~> 1.1) + - GoogleToolboxForMac/DebugUtils (2.1.1): + - GoogleToolboxForMac/Defines (= 2.1.1) + - GoogleToolboxForMac/Defines (2.1.1) + - GoogleToolboxForMac/Logger (2.1.1): + - GoogleToolboxForMac/Defines (= 2.1.1) + - GoogleToolboxForMac/NSData+zlib (2.1.1): + - GoogleToolboxForMac/Defines (= 2.1.1) + - GoogleToolboxForMac/NSDictionary+URLArguments (2.1.1): + - GoogleToolboxForMac/DebugUtils (= 2.1.1) + - GoogleToolboxForMac/Defines (= 2.1.1) + - GoogleToolboxForMac/NSString+URLArguments (= 2.1.1) + - GoogleToolboxForMac/NSString+URLArguments (2.1.1) + - GTMSessionFetcher/Core (1.1.8) + - Protobuf (3.2.0) + - React/Core (0.40.0): + - React/cxxreact + - React/yoga + - React/cxxreact (0.40.0): + - React/jschelpers + - React/jschelpers (0.40.0) + - React/RCTActionSheet (0.40.0): + - React/Core + - React/RCTAnimation (0.40.0): + - React/Core + - React/RCTCameraRoll (0.40.0): + - React/Core + - React/RCTImage + - React/RCTGeolocation (0.40.0): + - React/Core + - React/RCTImage (0.40.0): + - React/Core + - React/RCTNetwork + - React/RCTLinkingIOS (0.40.0): + - React/Core + - React/RCTNetwork (0.40.0): + - React/Core + - React/RCTPushNotification (0.40.0): + - React/Core + - React/RCTSettings (0.40.0): + - React/Core + - React/RCTText (0.40.0): + - React/Core + - React/RCTVibration (0.40.0): + - React/Core + - React/RCTWebSocket (0.40.0): + - React/Core + - React/yoga (0.40.0) + - RNFirebase (1.0.0-alpha13) + +DEPENDENCIES: + - Firebase/Analytics + - Firebase/AppIndexing + - Firebase/Auth + - Firebase/Core + - Firebase/Crash + - Firebase/Database + - Firebase/DynamicLinks + - Firebase/Messaging + - Firebase/RemoteConfig + - Firebase/Storage + - React/Core (from `../node_modules/react-native`) + - React/RCTActionSheet (from `../node_modules/react-native`) + - React/RCTAnimation (from `../node_modules/react-native`) + - React/RCTCameraRoll (from `../node_modules/react-native`) + - React/RCTGeolocation (from `../node_modules/react-native`) + - React/RCTImage (from `../node_modules/react-native`) + - React/RCTLinkingIOS (from `../node_modules/react-native`) + - React/RCTNetwork (from `../node_modules/react-native`) + - React/RCTPushNotification (from `../node_modules/react-native`) + - React/RCTSettings (from `../node_modules/react-native`) + - React/RCTText (from `../node_modules/react-native`) + - React/RCTVibration (from `../node_modules/react-native`) + - React/RCTWebSocket (from `../node_modules/react-native`) + - RNFirebase (from `./../../`) + +EXTERNAL SOURCES: + React: + :path: ../node_modules/react-native + RNFirebase: + :path: ./../../ + +SPEC CHECKSUMS: + Firebase: 85a581fb04e44f63ae9f4fbc8d6dabf4a4c18653 + FirebaseAnalytics: 0d1b7d81d5021155be37702a94ba1ec16d45365d + FirebaseAppIndexing: d0fa52ce0ad13f4b5b2f09e4b47fb0dc2213f4e9 + FirebaseAuth: cc8a1824170adbd351edb7f994490a3fb5c18be6 + FirebaseCore: 225d40532489835a034b8f4e2c9c87fbf4f615a2 + FirebaseCrash: db4c05d9c75baa050744d31b36357c8f1efba481 + FirebaseDatabase: 05c96d7b43a7368dc91c07791adb49683e1738d1 + FirebaseDynamicLinks: f0d025dd29a1d70418c003344813b67ab748ffb9 + FirebaseInstanceID: 2d0518b1378fe9d685ef40cbdd63d2fdc1125339 + FirebaseMessaging: df8267f378580a24174ce7861233aa11d5c90109 + FirebaseRemoteConfig: af3003f4e8daa2bd1d5cf90d3cccc1fe224f8ed9 + FirebaseStorage: a5c55b23741a49a72af8f30f95b3bb5ddbeda12d + GoogleToolboxForMac: 8e329f1b599f2512c6b10676d45736bcc2cbbeb0 + GTMSessionFetcher: 6f8d8b28b7e345549ac471071608170b31cb4977 + Protobuf: 745f59e122e5de98d4d7ef291e264a0eef80f58e + React: 6dfb2f72edb1d74a800127ae157af038646673ce + RNFirebase: 46bfe1099349ac6fac8c5e57cf4f0b0f4b7938ac + +PODFILE CHECKSUM: f8bc5de55afd159ec2faf523f1b8e0d861d0832b + +COCOAPODS: 1.2.0 diff --git a/tests/ios/ReactNativeFirebaseDemo-tvOS/Info.plist b/tests/ios/ReactNativeFirebaseDemo-tvOS/Info.plist new file mode 100644 index 00000000..2fb6a11c --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemo-tvOS/Info.plist @@ -0,0 +1,54 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIViewControllerBasedStatusBarAppearance + + NSLocationWhenInUseUsageDescription + + NSAppTransportSecurity + + + NSExceptionDomains + + localhost + + NSExceptionAllowsInsecureHTTPLoads + + + + + + diff --git a/tests/ios/ReactNativeFirebaseDemo-tvOSTests/Info.plist b/tests/ios/ReactNativeFirebaseDemo-tvOSTests/Info.plist new file mode 100644 index 00000000..886825cc --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemo-tvOSTests/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/tests/ios/ReactNativeFirebaseDemo.xcodeproj/project.pbxproj b/tests/ios/ReactNativeFirebaseDemo.xcodeproj/project.pbxproj new file mode 100644 index 00000000..de8d448e --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemo.xcodeproj/project.pbxproj @@ -0,0 +1,1537 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 00C302E51ABCBA2D00DB3ED1 /* libRCTActionSheet.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302AC1ABCB8CE00DB3ED1 /* libRCTActionSheet.a */; }; + 00C302E71ABCBA2D00DB3ED1 /* libRCTGeolocation.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302BA1ABCB90400DB3ED1 /* libRCTGeolocation.a */; }; + 00C302E81ABCBA2D00DB3ED1 /* libRCTImage.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302C01ABCB91800DB3ED1 /* libRCTImage.a */; }; + 00C302E91ABCBA2D00DB3ED1 /* libRCTNetwork.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */; }; + 00C302EA1ABCBA2D00DB3ED1 /* libRCTVibration.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */; }; + 00E356F31AD99517003FC87E /* ReactNativeFirebaseDemoTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* ReactNativeFirebaseDemoTests.m */; }; + 076B30A1D09C6AEEAE912DEB /* libPods-ReactNativeFirebaseDemo.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 42C7056622ACE9D1E626AD4C /* libPods-ReactNativeFirebaseDemo.a */; }; + 133E29F31AD74F7200F7D852 /* libRCTLinking.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 78C398B91ACF4ADC00677621 /* libRCTLinking.a */; }; + 139105C61AF99C1200B5F7CC /* libRCTSettings.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 139105C11AF99BAD00B5F7CC /* libRCTSettings.a */; }; + 139FDEF61B0652A700C62182 /* libRCTWebSocket.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 139FDEF41B06529B00C62182 /* libRCTWebSocket.a */; }; + 13B07FBC1A68108700A75B9A /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB01A68108700A75B9A /* AppDelegate.m */; }; + 13B07FBD1A68108700A75B9A /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB11A68108700A75B9A /* LaunchScreen.xib */; }; + 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; }; + 13B07FC11A68108700A75B9A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; }; + 140ED2AC1D01E1AD002B40FF /* libReact.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 146834041AC3E56700842450 /* libReact.a */; }; + 146834051AC3E58100842450 /* libReact.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 146834041AC3E56700842450 /* libReact.a */; }; + 1852BC611C674A2E905975BC /* Foundation.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 5F6AF99C2A6F4545B0F74832 /* Foundation.ttf */; }; + 211A77BD015F4D728A9B6E72 /* FontAwesome.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 7DD9301D866B4D52A7F83996 /* FontAwesome.ttf */; }; + 2D02E4BC1E0B4A80006451C7 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB01A68108700A75B9A /* AppDelegate.m */; }; + 2D02E4BD1E0B4A84006451C7 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; }; + 2D02E4BF1E0B4AB3006451C7 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; }; + 2D02E4C21E0B4AEC006451C7 /* libRCTAnimation-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5E9157351DD0AC6500FF2AA8 /* libRCTAnimation-tvOS.a */; }; + 2D02E4C31E0B4AEC006451C7 /* libRCTImage-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E841DF850E9000B6D8A /* libRCTImage-tvOS.a */; }; + 2D02E4C41E0B4AEC006451C7 /* libRCTLinking-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E881DF850E9000B6D8A /* libRCTLinking-tvOS.a */; }; + 2D02E4C51E0B4AEC006451C7 /* libRCTNetwork-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E8C1DF850E9000B6D8A /* libRCTNetwork-tvOS.a */; }; + 2D02E4C61E0B4AEC006451C7 /* libRCTSettings-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E901DF850E9000B6D8A /* libRCTSettings-tvOS.a */; }; + 2D02E4C71E0B4AEC006451C7 /* libRCTText-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E941DF850E9000B6D8A /* libRCTText-tvOS.a */; }; + 2D02E4C81E0B4AEC006451C7 /* libRCTWebSocket-tvOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3E991DF850E9000B6D8A /* libRCTWebSocket-tvOS.a */; }; + 2D02E4C91E0B4AEC006451C7 /* libReact.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3DAD3EA31DF850E9000B6D8A /* libReact.a */; }; + 2DCD954D1E0B4F2C00145EB5 /* ReactNativeFirebaseDemoTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* ReactNativeFirebaseDemoTests.m */; }; + 42A0E8F428A74B23B4C7D95A /* SimpleLineIcons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = FD3DFC8253C74B6298AFD3B7 /* SimpleLineIcons.ttf */; }; + 5E9157361DD0AC6A00FF2AA8 /* libRCTAnimation.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5E9157331DD0AC6500FF2AA8 /* libRCTAnimation.a */; }; + 644044EA167D431D96D0E6C1 /* libLRDRCTSimpleToast.a in Frameworks */ = {isa = PBXBuildFile; fileRef = BBEE706291534F5F948A3805 /* libLRDRCTSimpleToast.a */; }; + 6F307BC16AD047C8BD921730 /* MaterialCommunityIcons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 7A6F0C1C198B4A6FB4AB907D /* MaterialCommunityIcons.ttf */; }; + 82FE196A2ADC4D29BB2CB4BF /* Ionicons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 48961CCCEE8947FB9EE3658F /* Ionicons.ttf */; }; + 832341BD1AAA6AB300B99B32 /* libRCTText.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 832341B51AAA6A8300B99B32 /* libRCTText.a */; }; + 885057F5D1FA461AAAE0B487 /* Octicons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = CC24EB30F0484352BD65FFC1 /* Octicons.ttf */; }; + 8EE7622C1E718A8600B1E0F6 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 8EE7622B1E718A8600B1E0F6 /* GoogleService-Info.plist */; }; + 9D2381E3C2D340BA9A0737E2 /* MaterialIcons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 739DB016E64944BE99C338C4 /* MaterialIcons.ttf */; }; + D46EBD0604CE40EFB18F8A35 /* Zocial.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 182271FFECD74C3B92960E1D /* Zocial.ttf */; }; + E51DA6317685417F97A59475 /* libRNVectorIcons.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 0C76E33ACF004369AEB318B1 /* libRNVectorIcons.a */; }; + EA30CACE4CB84AC1BAE59432 /* Entypo.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 4935BEDE99B9436581953E77 /* Entypo.ttf */; }; + F57EC9E3C5414A99821B73F4 /* EvilIcons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = DB5BB32AF70B41678974C6B4 /* EvilIcons.ttf */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 00C302AB1ABCB8CE00DB3ED1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 134814201AA4EA6300B7C361; + remoteInfo = RCTActionSheet; + }; + 00C302B91ABCB90400DB3ED1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 134814201AA4EA6300B7C361; + remoteInfo = RCTGeolocation; + }; + 00C302BF1ABCB91800DB3ED1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 58B5115D1A9E6B3D00147676; + remoteInfo = RCTImage; + }; + 00C302DB1ABCB9D200DB3ED1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 58B511DB1A9E6C8500147676; + remoteInfo = RCTNetwork; + }; + 00C302E31ABCB9EE00DB3ED1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 832C81801AAF6DEF007FA2F7; + remoteInfo = RCTVibration; + }; + 00E356F41AD99517003FC87E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 13B07F861A680F5B00A75B9A; + remoteInfo = ReactNativeFirebaseDemo; + }; + 139105C01AF99BAD00B5F7CC /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 134814201AA4EA6300B7C361; + remoteInfo = RCTSettings; + }; + 139FDEF31B06529B00C62182 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3C86DF461ADF2C930047B81A; + remoteInfo = RCTWebSocket; + }; + 146834031AC3E56700842450 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 83CBBA2E1A601D0E00E9B192; + remoteInfo = React; + }; + 2D02E4911E0B4A5D006451C7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 2D02E47A1E0B4A5D006451C7; + remoteInfo = "ReactNativeFirebaseDemo-tvOS"; + }; + 3DAD3E831DF850E9000B6D8A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 2D2A283A1D9B042B00D4039D; + remoteInfo = "RCTImage-tvOS"; + }; + 3DAD3E871DF850E9000B6D8A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 2D2A28471D9B043800D4039D; + remoteInfo = "RCTLinking-tvOS"; + }; + 3DAD3E8B1DF850E9000B6D8A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 2D2A28541D9B044C00D4039D; + remoteInfo = "RCTNetwork-tvOS"; + }; + 3DAD3E8F1DF850E9000B6D8A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 2D2A28611D9B046600D4039D; + remoteInfo = "RCTSettings-tvOS"; + }; + 3DAD3E931DF850E9000B6D8A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 2D2A287B1D9B048500D4039D; + remoteInfo = "RCTText-tvOS"; + }; + 3DAD3E981DF850E9000B6D8A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 2D2A28881D9B049200D4039D; + remoteInfo = "RCTWebSocket-tvOS"; + }; + 3DAD3EA21DF850E9000B6D8A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 2D2A28131D9B038B00D4039D; + remoteInfo = "React-tvOS"; + }; + 3DAD3EA41DF850E9000B6D8A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D3C059A1DE3340900C268FA; + remoteInfo = yoga; + }; + 3DAD3EA61DF850E9000B6D8A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D3C06751DE3340C00C268FA; + remoteInfo = "yoga-tvOS"; + }; + 3DAD3EA81DF850E9000B6D8A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D3CD9251DE5FBEC00167DC4; + remoteInfo = cxxreact; + }; + 3DAD3EAA1DF850E9000B6D8A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D3CD9321DE5FBEE00167DC4; + remoteInfo = "cxxreact-tvOS"; + }; + 3DAD3EAC1DF850E9000B6D8A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D3CD90B1DE5FBD600167DC4; + remoteInfo = jschelpers; + }; + 3DAD3EAE1DF850E9000B6D8A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 146833FF1AC3E56700842450 /* React.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 3D3CD9181DE5FBD800167DC4; + remoteInfo = "jschelpers-tvOS"; + }; + 5E9157321DD0AC6500FF2AA8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 134814201AA4EA6300B7C361; + remoteInfo = RCTAnimation; + }; + 5E9157341DD0AC6500FF2AA8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 2D2A28201D9B03D100D4039D; + remoteInfo = "RCTAnimation-tvOS"; + }; + 78C398B81ACF4ADC00677621 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 134814201AA4EA6300B7C361; + remoteInfo = RCTLinking; + }; + 832341B41AAA6A8300B99B32 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 58B5119B1A9E6C1200147676; + remoteInfo = RCTText; + }; + 997890041E69DE2900F6820C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = C7C48FEEC8E34DE4BB5DE211 /* RNFirebase.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = E26E29F41BBE54B800BF9CD9; + remoteInfo = RNFirebase; + }; + 997890071E69DE2900F6820C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 8BE028F5B04B4DC3BEF0305F /* RNVectorIcons.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 5DBEB1501B18CEA900B34395; + remoteInfo = RNVectorIcons; + }; + 997890191E6D86E700F6820C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 78C4D9D5FCAA43A384C23C35 /* LRDRCTSimpleToast.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 15209BEF1D250F63000D0F44; + remoteInfo = LRDRCTSimpleToast; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 008F07F21AC5B25A0029DE68 /* main.jsbundle */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = main.jsbundle; sourceTree = ""; }; + 00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTActionSheet.xcodeproj; path = "../node_modules/react-native/Libraries/ActionSheetIOS/RCTActionSheet.xcodeproj"; sourceTree = ""; }; + 00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTGeolocation.xcodeproj; path = "../node_modules/react-native/Libraries/Geolocation/RCTGeolocation.xcodeproj"; sourceTree = ""; }; + 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTImage.xcodeproj; path = "../node_modules/react-native/Libraries/Image/RCTImage.xcodeproj"; sourceTree = ""; }; + 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTNetwork.xcodeproj; path = "../node_modules/react-native/Libraries/Network/RCTNetwork.xcodeproj"; sourceTree = ""; }; + 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTVibration.xcodeproj; path = "../node_modules/react-native/Libraries/Vibration/RCTVibration.xcodeproj"; sourceTree = ""; }; + 00E356EE1AD99517003FC87E /* ReactNativeFirebaseDemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = ReactNativeFirebaseDemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 00E356F11AD99517003FC87E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 00E356F21AD99517003FC87E /* ReactNativeFirebaseDemoTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ReactNativeFirebaseDemoTests.m; sourceTree = ""; }; + 07C05CEFA32C3C442CA152DB /* Pods-ReactNativeFirebaseDemo.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ReactNativeFirebaseDemo.debug.xcconfig"; path = "Pods/Target Support Files/Pods-ReactNativeFirebaseDemo/Pods-ReactNativeFirebaseDemo.debug.xcconfig"; sourceTree = ""; }; + 0C76E33ACF004369AEB318B1 /* libRNVectorIcons.a */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = archive.ar; path = libRNVectorIcons.a; sourceTree = ""; }; + 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTSettings.xcodeproj; path = "../node_modules/react-native/Libraries/Settings/RCTSettings.xcodeproj"; sourceTree = ""; }; + 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTWebSocket.xcodeproj; path = "../node_modules/react-native/Libraries/WebSocket/RCTWebSocket.xcodeproj"; sourceTree = ""; }; + 13B07F961A680F5B00A75B9A /* ReactNativeFirebaseDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ReactNativeFirebaseDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 13B07FAF1A68108700A75B9A /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = ReactNativeFirebaseDemo/AppDelegate.h; sourceTree = ""; }; + 13B07FB01A68108700A75B9A /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AppDelegate.m; path = ReactNativeFirebaseDemo/AppDelegate.m; sourceTree = ""; }; + 13B07FB21A68108700A75B9A /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/LaunchScreen.xib; sourceTree = ""; }; + 13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = ReactNativeFirebaseDemo/Images.xcassets; sourceTree = ""; }; + 13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = ReactNativeFirebaseDemo/Info.plist; sourceTree = ""; }; + 13B07FB71A68108700A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = ReactNativeFirebaseDemo/main.m; sourceTree = ""; }; + 146833FF1AC3E56700842450 /* React.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = React.xcodeproj; path = "../node_modules/react-native/React/React.xcodeproj"; sourceTree = ""; }; + 182271FFECD74C3B92960E1D /* Zocial.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Zocial.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Zocial.ttf"; sourceTree = ""; }; + 2D02E47B1E0B4A5D006451C7 /* ReactNativeFirebaseDemo-tvOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "ReactNativeFirebaseDemo-tvOS.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 2D02E4901E0B4A5D006451C7 /* ReactNativeFirebaseDemo-tvOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "ReactNativeFirebaseDemo-tvOSTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + 42C7056622ACE9D1E626AD4C /* libPods-ReactNativeFirebaseDemo.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-ReactNativeFirebaseDemo.a"; sourceTree = BUILT_PRODUCTS_DIR; }; + 48961CCCEE8947FB9EE3658F /* Ionicons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Ionicons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Ionicons.ttf"; sourceTree = ""; }; + 4935BEDE99B9436581953E77 /* Entypo.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Entypo.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Entypo.ttf"; sourceTree = ""; }; + 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTAnimation.xcodeproj; path = "../node_modules/react-native/Libraries/NativeAnimation/RCTAnimation.xcodeproj"; sourceTree = ""; }; + 5F6AF99C2A6F4545B0F74832 /* Foundation.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Foundation.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Foundation.ttf"; sourceTree = ""; }; + 739DB016E64944BE99C338C4 /* MaterialIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = MaterialIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/MaterialIcons.ttf"; sourceTree = ""; }; + 7791402B6343C1906BE4D13A /* libPods-ReactNativeFirebaseDemoTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-ReactNativeFirebaseDemoTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; + 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTLinking.xcodeproj; path = "../node_modules/react-native/Libraries/LinkingIOS/RCTLinking.xcodeproj"; sourceTree = ""; }; + 78C4D9D5FCAA43A384C23C35 /* LRDRCTSimpleToast.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = "wrapper.pb-project"; name = LRDRCTSimpleToast.xcodeproj; path = "../node_modules/react-native-simple-toast/ios/LRDRCTSimpleToast.xcodeproj"; sourceTree = ""; }; + 7A6F0C1C198B4A6FB4AB907D /* MaterialCommunityIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = MaterialCommunityIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/MaterialCommunityIcons.ttf"; sourceTree = ""; }; + 7DD9301D866B4D52A7F83996 /* FontAwesome.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = FontAwesome.ttf; path = "../node_modules/react-native-vector-icons/Fonts/FontAwesome.ttf"; sourceTree = ""; }; + 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = RCTText.xcodeproj; path = "../node_modules/react-native/Libraries/Text/RCTText.xcodeproj"; sourceTree = ""; }; + 8BE028F5B04B4DC3BEF0305F /* RNVectorIcons.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = "wrapper.pb-project"; name = RNVectorIcons.xcodeproj; path = "../node_modules/react-native-vector-icons/RNVectorIcons.xcodeproj"; sourceTree = ""; }; + 8EE7622B1E718A8600B1E0F6 /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; + 93FF19757985B70080544398 /* Pods-ReactNativeFirebaseDemo.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-ReactNativeFirebaseDemo.release.xcconfig"; path = "Pods/Target Support Files/Pods-ReactNativeFirebaseDemo/Pods-ReactNativeFirebaseDemo.release.xcconfig"; sourceTree = ""; }; + BBEE706291534F5F948A3805 /* libLRDRCTSimpleToast.a */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = archive.ar; path = libLRDRCTSimpleToast.a; sourceTree = ""; }; + C7C48FEEC8E34DE4BB5DE211 /* RNFirebase.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = "wrapper.pb-project"; name = RNFirebase.xcodeproj; path = "../node_modules/react-native-firebase/RNFirebase.xcodeproj"; sourceTree = ""; }; + CC24EB30F0484352BD65FFC1 /* Octicons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Octicons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/Octicons.ttf"; sourceTree = ""; }; + DB5BB32AF70B41678974C6B4 /* EvilIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = EvilIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/EvilIcons.ttf"; sourceTree = ""; }; + FD3DFC8253C74B6298AFD3B7 /* SimpleLineIcons.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = SimpleLineIcons.ttf; path = "../node_modules/react-native-vector-icons/Fonts/SimpleLineIcons.ttf"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 00E356EB1AD99517003FC87E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 140ED2AC1D01E1AD002B40FF /* libReact.a in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 13B07F8C1A680F5B00A75B9A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 146834051AC3E58100842450 /* libReact.a in Frameworks */, + 5E9157361DD0AC6A00FF2AA8 /* libRCTAnimation.a in Frameworks */, + 00C302E51ABCBA2D00DB3ED1 /* libRCTActionSheet.a in Frameworks */, + 00C302E71ABCBA2D00DB3ED1 /* libRCTGeolocation.a in Frameworks */, + 00C302E81ABCBA2D00DB3ED1 /* libRCTImage.a in Frameworks */, + 133E29F31AD74F7200F7D852 /* libRCTLinking.a in Frameworks */, + 00C302E91ABCBA2D00DB3ED1 /* libRCTNetwork.a in Frameworks */, + 139105C61AF99C1200B5F7CC /* libRCTSettings.a in Frameworks */, + 832341BD1AAA6AB300B99B32 /* libRCTText.a in Frameworks */, + 00C302EA1ABCBA2D00DB3ED1 /* libRCTVibration.a in Frameworks */, + 139FDEF61B0652A700C62182 /* libRCTWebSocket.a in Frameworks */, + E51DA6317685417F97A59475 /* libRNVectorIcons.a in Frameworks */, + 644044EA167D431D96D0E6C1 /* libLRDRCTSimpleToast.a in Frameworks */, + 076B30A1D09C6AEEAE912DEB /* libPods-ReactNativeFirebaseDemo.a in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2D02E4781E0B4A5D006451C7 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2D02E4C91E0B4AEC006451C7 /* libReact.a in Frameworks */, + 2D02E4C21E0B4AEC006451C7 /* libRCTAnimation-tvOS.a in Frameworks */, + 2D02E4C31E0B4AEC006451C7 /* libRCTImage-tvOS.a in Frameworks */, + 2D02E4C41E0B4AEC006451C7 /* libRCTLinking-tvOS.a in Frameworks */, + 2D02E4C51E0B4AEC006451C7 /* libRCTNetwork-tvOS.a in Frameworks */, + 2D02E4C61E0B4AEC006451C7 /* libRCTSettings-tvOS.a in Frameworks */, + 2D02E4C71E0B4AEC006451C7 /* libRCTText-tvOS.a in Frameworks */, + 2D02E4C81E0B4AEC006451C7 /* libRCTWebSocket-tvOS.a in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2D02E48D1E0B4A5D006451C7 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 00C302A81ABCB8CE00DB3ED1 /* Products */ = { + isa = PBXGroup; + children = ( + 00C302AC1ABCB8CE00DB3ED1 /* libRCTActionSheet.a */, + ); + name = Products; + sourceTree = ""; + }; + 00C302B61ABCB90400DB3ED1 /* Products */ = { + isa = PBXGroup; + children = ( + 00C302BA1ABCB90400DB3ED1 /* libRCTGeolocation.a */, + ); + name = Products; + sourceTree = ""; + }; + 00C302BC1ABCB91800DB3ED1 /* Products */ = { + isa = PBXGroup; + children = ( + 00C302C01ABCB91800DB3ED1 /* libRCTImage.a */, + 3DAD3E841DF850E9000B6D8A /* libRCTImage-tvOS.a */, + ); + name = Products; + sourceTree = ""; + }; + 00C302D41ABCB9D200DB3ED1 /* Products */ = { + isa = PBXGroup; + children = ( + 00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */, + 3DAD3E8C1DF850E9000B6D8A /* libRCTNetwork-tvOS.a */, + ); + name = Products; + sourceTree = ""; + }; + 00C302E01ABCB9EE00DB3ED1 /* Products */ = { + isa = PBXGroup; + children = ( + 00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */, + ); + name = Products; + sourceTree = ""; + }; + 00E356EF1AD99517003FC87E /* ReactNativeFirebaseDemoTests */ = { + isa = PBXGroup; + children = ( + 00E356F21AD99517003FC87E /* ReactNativeFirebaseDemoTests.m */, + 00E356F01AD99517003FC87E /* Supporting Files */, + ); + path = ReactNativeFirebaseDemoTests; + sourceTree = ""; + }; + 00E356F01AD99517003FC87E /* Supporting Files */ = { + isa = PBXGroup; + children = ( + 00E356F11AD99517003FC87E /* Info.plist */, + ); + name = "Supporting Files"; + sourceTree = ""; + }; + 0D55D6BB72314357439E4EE9 /* Pods */ = { + isa = PBXGroup; + children = ( + 07C05CEFA32C3C442CA152DB /* Pods-ReactNativeFirebaseDemo.debug.xcconfig */, + 93FF19757985B70080544398 /* Pods-ReactNativeFirebaseDemo.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; + 139105B71AF99BAD00B5F7CC /* Products */ = { + isa = PBXGroup; + children = ( + 139105C11AF99BAD00B5F7CC /* libRCTSettings.a */, + 3DAD3E901DF850E9000B6D8A /* libRCTSettings-tvOS.a */, + ); + name = Products; + sourceTree = ""; + }; + 139FDEE71B06529A00C62182 /* Products */ = { + isa = PBXGroup; + children = ( + 139FDEF41B06529B00C62182 /* libRCTWebSocket.a */, + 3DAD3E991DF850E9000B6D8A /* libRCTWebSocket-tvOS.a */, + ); + name = Products; + sourceTree = ""; + }; + 13B07FAE1A68108700A75B9A /* ReactNativeFirebaseDemo */ = { + isa = PBXGroup; + children = ( + 8EE7622B1E718A8600B1E0F6 /* GoogleService-Info.plist */, + 008F07F21AC5B25A0029DE68 /* main.jsbundle */, + 13B07FAF1A68108700A75B9A /* AppDelegate.h */, + 13B07FB01A68108700A75B9A /* AppDelegate.m */, + 13B07FB51A68108700A75B9A /* Images.xcassets */, + 13B07FB61A68108700A75B9A /* Info.plist */, + 13B07FB11A68108700A75B9A /* LaunchScreen.xib */, + 13B07FB71A68108700A75B9A /* main.m */, + ); + name = ReactNativeFirebaseDemo; + sourceTree = ""; + }; + 146834001AC3E56700842450 /* Products */ = { + isa = PBXGroup; + children = ( + 146834041AC3E56700842450 /* libReact.a */, + 3DAD3EA31DF850E9000B6D8A /* libReact.a */, + 3DAD3EA51DF850E9000B6D8A /* libyoga.a */, + 3DAD3EA71DF850E9000B6D8A /* libyoga.a */, + 3DAD3EA91DF850E9000B6D8A /* libcxxreact.a */, + 3DAD3EAB1DF850E9000B6D8A /* libcxxreact.a */, + 3DAD3EAD1DF850E9000B6D8A /* libjschelpers.a */, + 3DAD3EAF1DF850E9000B6D8A /* libjschelpers.a */, + ); + name = Products; + sourceTree = ""; + }; + 3F2926F67DDFAB9753757355 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 42C7056622ACE9D1E626AD4C /* libPods-ReactNativeFirebaseDemo.a */, + 7791402B6343C1906BE4D13A /* libPods-ReactNativeFirebaseDemoTests.a */, + ); + name = Frameworks; + sourceTree = ""; + }; + 5E91572E1DD0AC6500FF2AA8 /* Products */ = { + isa = PBXGroup; + children = ( + 5E9157331DD0AC6500FF2AA8 /* libRCTAnimation.a */, + 5E9157351DD0AC6500FF2AA8 /* libRCTAnimation-tvOS.a */, + ); + name = Products; + sourceTree = ""; + }; + 78C398B11ACF4ADC00677621 /* Products */ = { + isa = PBXGroup; + children = ( + 78C398B91ACF4ADC00677621 /* libRCTLinking.a */, + 3DAD3E881DF850E9000B6D8A /* libRCTLinking-tvOS.a */, + ); + name = Products; + sourceTree = ""; + }; + 832341AE1AAA6A7D00B99B32 /* Libraries */ = { + isa = PBXGroup; + children = ( + 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */, + 146833FF1AC3E56700842450 /* React.xcodeproj */, + 00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */, + 00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */, + 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */, + 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */, + 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */, + 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */, + 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */, + 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */, + 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */, + C7C48FEEC8E34DE4BB5DE211 /* RNFirebase.xcodeproj */, + 8BE028F5B04B4DC3BEF0305F /* RNVectorIcons.xcodeproj */, + 78C4D9D5FCAA43A384C23C35 /* LRDRCTSimpleToast.xcodeproj */, + ); + name = Libraries; + sourceTree = ""; + }; + 832341B11AAA6A8300B99B32 /* Products */ = { + isa = PBXGroup; + children = ( + 832341B51AAA6A8300B99B32 /* libRCTText.a */, + 3DAD3E941DF850E9000B6D8A /* libRCTText-tvOS.a */, + ); + name = Products; + sourceTree = ""; + }; + 83CBB9F61A601CBA00E9B192 = { + isa = PBXGroup; + children = ( + 13B07FAE1A68108700A75B9A /* ReactNativeFirebaseDemo */, + 832341AE1AAA6A7D00B99B32 /* Libraries */, + 00E356EF1AD99517003FC87E /* ReactNativeFirebaseDemoTests */, + 83CBBA001A601CBA00E9B192 /* Products */, + F50F62EA16044AFF8BD7CF63 /* Resources */, + 0D55D6BB72314357439E4EE9 /* Pods */, + 3F2926F67DDFAB9753757355 /* Frameworks */, + ); + indentWidth = 2; + sourceTree = ""; + tabWidth = 2; + }; + 83CBBA001A601CBA00E9B192 /* Products */ = { + isa = PBXGroup; + children = ( + 13B07F961A680F5B00A75B9A /* ReactNativeFirebaseDemo.app */, + 00E356EE1AD99517003FC87E /* ReactNativeFirebaseDemoTests.xctest */, + 2D02E47B1E0B4A5D006451C7 /* ReactNativeFirebaseDemo-tvOS.app */, + 2D02E4901E0B4A5D006451C7 /* ReactNativeFirebaseDemo-tvOSTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 99788FE61E69DE2900F6820C /* Products */ = { + isa = PBXGroup; + children = ( + 997890051E69DE2900F6820C /* RNFirebase.framework */, + ); + name = Products; + sourceTree = ""; + }; + 99788FE81E69DE2900F6820C /* Products */ = { + isa = PBXGroup; + children = ( + 997890081E69DE2900F6820C /* libRNVectorIcons.a */, + ); + name = Products; + sourceTree = ""; + }; + 997890161E6D86E700F6820C /* Products */ = { + isa = PBXGroup; + children = ( + 9978901A1E6D86E700F6820C /* libLRDRCTSimpleToast.a */, + ); + name = Products; + sourceTree = ""; + }; + F50F62EA16044AFF8BD7CF63 /* Resources */ = { + isa = PBXGroup; + children = ( + 4935BEDE99B9436581953E77 /* Entypo.ttf */, + DB5BB32AF70B41678974C6B4 /* EvilIcons.ttf */, + 7DD9301D866B4D52A7F83996 /* FontAwesome.ttf */, + 5F6AF99C2A6F4545B0F74832 /* Foundation.ttf */, + 48961CCCEE8947FB9EE3658F /* Ionicons.ttf */, + 7A6F0C1C198B4A6FB4AB907D /* MaterialCommunityIcons.ttf */, + 739DB016E64944BE99C338C4 /* MaterialIcons.ttf */, + CC24EB30F0484352BD65FFC1 /* Octicons.ttf */, + FD3DFC8253C74B6298AFD3B7 /* SimpleLineIcons.ttf */, + 182271FFECD74C3B92960E1D /* Zocial.ttf */, + ); + name = Resources; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 00E356ED1AD99517003FC87E /* ReactNativeFirebaseDemoTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "ReactNativeFirebaseDemoTests" */; + buildPhases = ( + 00E356EA1AD99517003FC87E /* Sources */, + 00E356EB1AD99517003FC87E /* Frameworks */, + 00E356EC1AD99517003FC87E /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 00E356F51AD99517003FC87E /* PBXTargetDependency */, + ); + name = ReactNativeFirebaseDemoTests; + productName = ReactNativeFirebaseDemoTests; + productReference = 00E356EE1AD99517003FC87E /* ReactNativeFirebaseDemoTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 13B07F861A680F5B00A75B9A /* ReactNativeFirebaseDemo */ = { + isa = PBXNativeTarget; + buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "ReactNativeFirebaseDemo" */; + buildPhases = ( + 26F9B43687A3EAE646F8970D /* [CP] Check Pods Manifest.lock */, + 13B07F871A680F5B00A75B9A /* Sources */, + 13B07F8C1A680F5B00A75B9A /* Frameworks */, + 13B07F8E1A680F5B00A75B9A /* Resources */, + 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */, + C015646CE8F8CB4B578CE178 /* [CP] Embed Pods Frameworks */, + 6AE1012F46FF8A4D1D818A12 /* [CP] Copy Pods Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = ReactNativeFirebaseDemo; + productName = "Hello World"; + productReference = 13B07F961A680F5B00A75B9A /* ReactNativeFirebaseDemo.app */; + productType = "com.apple.product-type.application"; + }; + 2D02E47A1E0B4A5D006451C7 /* ReactNativeFirebaseDemo-tvOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2D02E4BA1E0B4A5E006451C7 /* Build configuration list for PBXNativeTarget "ReactNativeFirebaseDemo-tvOS" */; + buildPhases = ( + 2D02E4771E0B4A5D006451C7 /* Sources */, + 2D02E4781E0B4A5D006451C7 /* Frameworks */, + 2D02E4791E0B4A5D006451C7 /* Resources */, + 2D02E4CB1E0B4B27006451C7 /* Bundle React Native Code And Images */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "ReactNativeFirebaseDemo-tvOS"; + productName = "ReactNativeFirebaseDemo-tvOS"; + productReference = 2D02E47B1E0B4A5D006451C7 /* ReactNativeFirebaseDemo-tvOS.app */; + productType = "com.apple.product-type.application"; + }; + 2D02E48F1E0B4A5D006451C7 /* ReactNativeFirebaseDemo-tvOSTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2D02E4BB1E0B4A5E006451C7 /* Build configuration list for PBXNativeTarget "ReactNativeFirebaseDemo-tvOSTests" */; + buildPhases = ( + 2D02E48C1E0B4A5D006451C7 /* Sources */, + 2D02E48D1E0B4A5D006451C7 /* Frameworks */, + 2D02E48E1E0B4A5D006451C7 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 2D02E4921E0B4A5D006451C7 /* PBXTargetDependency */, + ); + name = "ReactNativeFirebaseDemo-tvOSTests"; + productName = "ReactNativeFirebaseDemo-tvOSTests"; + productReference = 2D02E4901E0B4A5D006451C7 /* ReactNativeFirebaseDemo-tvOSTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 83CBB9F71A601CBA00E9B192 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 610; + ORGANIZATIONNAME = Facebook; + TargetAttributes = { + 00E356ED1AD99517003FC87E = { + CreatedOnToolsVersion = 6.2; + TestTargetID = 13B07F861A680F5B00A75B9A; + }; + 2D02E47A1E0B4A5D006451C7 = { + CreatedOnToolsVersion = 8.2.1; + ProvisioningStyle = Automatic; + }; + 2D02E48F1E0B4A5D006451C7 = { + CreatedOnToolsVersion = 8.2.1; + ProvisioningStyle = Automatic; + TestTargetID = 2D02E47A1E0B4A5D006451C7; + }; + }; + }; + buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "ReactNativeFirebaseDemo" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 83CBB9F61A601CBA00E9B192; + productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */; + projectDirPath = ""; + projectReferences = ( + { + ProductGroup = 997890161E6D86E700F6820C /* Products */; + ProjectRef = 78C4D9D5FCAA43A384C23C35 /* LRDRCTSimpleToast.xcodeproj */; + }, + { + ProductGroup = 00C302A81ABCB8CE00DB3ED1 /* Products */; + ProjectRef = 00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */; + }, + { + ProductGroup = 5E91572E1DD0AC6500FF2AA8 /* Products */; + ProjectRef = 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */; + }, + { + ProductGroup = 00C302B61ABCB90400DB3ED1 /* Products */; + ProjectRef = 00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */; + }, + { + ProductGroup = 00C302BC1ABCB91800DB3ED1 /* Products */; + ProjectRef = 00C302BB1ABCB91800DB3ED1 /* RCTImage.xcodeproj */; + }, + { + ProductGroup = 78C398B11ACF4ADC00677621 /* Products */; + ProjectRef = 78C398B01ACF4ADC00677621 /* RCTLinking.xcodeproj */; + }, + { + ProductGroup = 00C302D41ABCB9D200DB3ED1 /* Products */; + ProjectRef = 00C302D31ABCB9D200DB3ED1 /* RCTNetwork.xcodeproj */; + }, + { + ProductGroup = 139105B71AF99BAD00B5F7CC /* Products */; + ProjectRef = 139105B61AF99BAD00B5F7CC /* RCTSettings.xcodeproj */; + }, + { + ProductGroup = 832341B11AAA6A8300B99B32 /* Products */; + ProjectRef = 832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */; + }, + { + ProductGroup = 00C302E01ABCB9EE00DB3ED1 /* Products */; + ProjectRef = 00C302DF1ABCB9EE00DB3ED1 /* RCTVibration.xcodeproj */; + }, + { + ProductGroup = 139FDEE71B06529A00C62182 /* Products */; + ProjectRef = 139FDEE61B06529A00C62182 /* RCTWebSocket.xcodeproj */; + }, + { + ProductGroup = 146834001AC3E56700842450 /* Products */; + ProjectRef = 146833FF1AC3E56700842450 /* React.xcodeproj */; + }, + { + ProductGroup = 99788FE61E69DE2900F6820C /* Products */; + ProjectRef = C7C48FEEC8E34DE4BB5DE211 /* RNFirebase.xcodeproj */; + }, + { + ProductGroup = 99788FE81E69DE2900F6820C /* Products */; + ProjectRef = 8BE028F5B04B4DC3BEF0305F /* RNVectorIcons.xcodeproj */; + }, + ); + projectRoot = ""; + targets = ( + 13B07F861A680F5B00A75B9A /* ReactNativeFirebaseDemo */, + 00E356ED1AD99517003FC87E /* ReactNativeFirebaseDemoTests */, + 2D02E47A1E0B4A5D006451C7 /* ReactNativeFirebaseDemo-tvOS */, + 2D02E48F1E0B4A5D006451C7 /* ReactNativeFirebaseDemo-tvOSTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXReferenceProxy section */ + 00C302AC1ABCB8CE00DB3ED1 /* libRCTActionSheet.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libRCTActionSheet.a; + remoteRef = 00C302AB1ABCB8CE00DB3ED1 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 00C302BA1ABCB90400DB3ED1 /* libRCTGeolocation.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libRCTGeolocation.a; + remoteRef = 00C302B91ABCB90400DB3ED1 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 00C302C01ABCB91800DB3ED1 /* libRCTImage.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libRCTImage.a; + remoteRef = 00C302BF1ABCB91800DB3ED1 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 00C302DC1ABCB9D200DB3ED1 /* libRCTNetwork.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libRCTNetwork.a; + remoteRef = 00C302DB1ABCB9D200DB3ED1 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 00C302E41ABCB9EE00DB3ED1 /* libRCTVibration.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libRCTVibration.a; + remoteRef = 00C302E31ABCB9EE00DB3ED1 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 139105C11AF99BAD00B5F7CC /* libRCTSettings.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libRCTSettings.a; + remoteRef = 139105C01AF99BAD00B5F7CC /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 139FDEF41B06529B00C62182 /* libRCTWebSocket.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libRCTWebSocket.a; + remoteRef = 139FDEF31B06529B00C62182 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 146834041AC3E56700842450 /* libReact.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libReact.a; + remoteRef = 146834031AC3E56700842450 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 3DAD3E841DF850E9000B6D8A /* libRCTImage-tvOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libRCTImage-tvOS.a"; + remoteRef = 3DAD3E831DF850E9000B6D8A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 3DAD3E881DF850E9000B6D8A /* libRCTLinking-tvOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libRCTLinking-tvOS.a"; + remoteRef = 3DAD3E871DF850E9000B6D8A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 3DAD3E8C1DF850E9000B6D8A /* libRCTNetwork-tvOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libRCTNetwork-tvOS.a"; + remoteRef = 3DAD3E8B1DF850E9000B6D8A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 3DAD3E901DF850E9000B6D8A /* libRCTSettings-tvOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libRCTSettings-tvOS.a"; + remoteRef = 3DAD3E8F1DF850E9000B6D8A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 3DAD3E941DF850E9000B6D8A /* libRCTText-tvOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libRCTText-tvOS.a"; + remoteRef = 3DAD3E931DF850E9000B6D8A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 3DAD3E991DF850E9000B6D8A /* libRCTWebSocket-tvOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libRCTWebSocket-tvOS.a"; + remoteRef = 3DAD3E981DF850E9000B6D8A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 3DAD3EA31DF850E9000B6D8A /* libReact.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libReact.a; + remoteRef = 3DAD3EA21DF850E9000B6D8A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 3DAD3EA51DF850E9000B6D8A /* libyoga.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libyoga.a; + remoteRef = 3DAD3EA41DF850E9000B6D8A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 3DAD3EA71DF850E9000B6D8A /* libyoga.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libyoga.a; + remoteRef = 3DAD3EA61DF850E9000B6D8A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 3DAD3EA91DF850E9000B6D8A /* libcxxreact.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libcxxreact.a; + remoteRef = 3DAD3EA81DF850E9000B6D8A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 3DAD3EAB1DF850E9000B6D8A /* libcxxreact.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libcxxreact.a; + remoteRef = 3DAD3EAA1DF850E9000B6D8A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 3DAD3EAD1DF850E9000B6D8A /* libjschelpers.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libjschelpers.a; + remoteRef = 3DAD3EAC1DF850E9000B6D8A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 3DAD3EAF1DF850E9000B6D8A /* libjschelpers.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libjschelpers.a; + remoteRef = 3DAD3EAE1DF850E9000B6D8A /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 5E9157331DD0AC6500FF2AA8 /* libRCTAnimation.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libRCTAnimation.a; + remoteRef = 5E9157321DD0AC6500FF2AA8 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 5E9157351DD0AC6500FF2AA8 /* libRCTAnimation-tvOS.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = "libRCTAnimation-tvOS.a"; + remoteRef = 5E9157341DD0AC6500FF2AA8 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 78C398B91ACF4ADC00677621 /* libRCTLinking.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libRCTLinking.a; + remoteRef = 78C398B81ACF4ADC00677621 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 832341B51AAA6A8300B99B32 /* libRCTText.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libRCTText.a; + remoteRef = 832341B41AAA6A8300B99B32 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 997890051E69DE2900F6820C /* RNFirebase.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = RNFirebase.framework; + remoteRef = 997890041E69DE2900F6820C /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 997890081E69DE2900F6820C /* libRNVectorIcons.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libRNVectorIcons.a; + remoteRef = 997890071E69DE2900F6820C /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 9978901A1E6D86E700F6820C /* libLRDRCTSimpleToast.a */ = { + isa = PBXReferenceProxy; + fileType = archive.ar; + path = libLRDRCTSimpleToast.a; + remoteRef = 997890191E6D86E700F6820C /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + +/* Begin PBXResourcesBuildPhase section */ + 00E356EC1AD99517003FC87E /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 13B07F8E1A680F5B00A75B9A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8EE7622C1E718A8600B1E0F6 /* GoogleService-Info.plist in Resources */, + 13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */, + 13B07FBD1A68108700A75B9A /* LaunchScreen.xib in Resources */, + EA30CACE4CB84AC1BAE59432 /* Entypo.ttf in Resources */, + F57EC9E3C5414A99821B73F4 /* EvilIcons.ttf in Resources */, + 211A77BD015F4D728A9B6E72 /* FontAwesome.ttf in Resources */, + 1852BC611C674A2E905975BC /* Foundation.ttf in Resources */, + 82FE196A2ADC4D29BB2CB4BF /* Ionicons.ttf in Resources */, + 6F307BC16AD047C8BD921730 /* MaterialCommunityIcons.ttf in Resources */, + 9D2381E3C2D340BA9A0737E2 /* MaterialIcons.ttf in Resources */, + 885057F5D1FA461AAAE0B487 /* Octicons.ttf in Resources */, + 42A0E8F428A74B23B4C7D95A /* SimpleLineIcons.ttf in Resources */, + D46EBD0604CE40EFB18F8A35 /* Zocial.ttf in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2D02E4791E0B4A5D006451C7 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2D02E4BD1E0B4A84006451C7 /* Images.xcassets in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2D02E48E1E0B4A5D006451C7 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Bundle React Native code and images"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "export NODE_BINARY=node\n../node_modules/react-native/packager/react-native-xcode.sh"; + }; + 26F9B43687A3EAE646F8970D /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + 2D02E4CB1E0B4B27006451C7 /* Bundle React Native Code And Images */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Bundle React Native Code And Images"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "export NODE_BINARY=node\n../node_modules/react-native/packager/react-native-xcode.sh"; + }; + 6AE1012F46FF8A4D1D818A12 /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-ReactNativeFirebaseDemo/Pods-ReactNativeFirebaseDemo-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; + C015646CE8F8CB4B578CE178 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-ReactNativeFirebaseDemo/Pods-ReactNativeFirebaseDemo-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 00E356EA1AD99517003FC87E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 00E356F31AD99517003FC87E /* ReactNativeFirebaseDemoTests.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 13B07F871A680F5B00A75B9A /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 13B07FBC1A68108700A75B9A /* AppDelegate.m in Sources */, + 13B07FC11A68108700A75B9A /* main.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2D02E4771E0B4A5D006451C7 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2D02E4BF1E0B4AB3006451C7 /* main.m in Sources */, + 2D02E4BC1E0B4A80006451C7 /* AppDelegate.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2D02E48C1E0B4A5D006451C7 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2DCD954D1E0B4F2C00145EB5 /* ReactNativeFirebaseDemoTests.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 00E356F51AD99517003FC87E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 13B07F861A680F5B00A75B9A /* ReactNativeFirebaseDemo */; + targetProxy = 00E356F41AD99517003FC87E /* PBXContainerItemProxy */; + }; + 2D02E4921E0B4A5D006451C7 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 2D02E47A1E0B4A5D006451C7 /* ReactNativeFirebaseDemo-tvOS */; + targetProxy = 2D02E4911E0B4A5D006451C7 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 13B07FB11A68108700A75B9A /* LaunchScreen.xib */ = { + isa = PBXVariantGroup; + children = ( + 13B07FB21A68108700A75B9A /* Base */, + ); + name = LaunchScreen.xib; + path = ReactNativeFirebaseDemo; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 00E356F61AD99517003FC87E /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "$(SRCROOT)/../node_modules/react-native-firebase/Firebase.framework/Headers/**", + "$(SRCROOT)/../node_modules/react-native-vector-icons/RNVectorIconsManager", + "$(SRCROOT)/../node_modules/react-native-simple-toast/ios/LRDRCTSimpleToast", + ); + INFOPLIST_FILE = ReactNativeFirebaseDemoTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "\"$(SRCROOT)/$(TARGET_NAME)\"", + "\"$(SRCROOT)/$(TARGET_NAME)\"", + ); + OTHER_LDFLAGS = ( + "-ObjC", + "-lc++", + ); + PRODUCT_NAME = "$(TARGET_NAME)"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/ReactNativeFirebaseDemo.app/ReactNativeFirebaseDemo"; + }; + name = Debug; + }; + 00E356F71AD99517003FC87E /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + COPY_PHASE_STRIP = NO; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "$(SRCROOT)/../node_modules/react-native-firebase/Firebase.framework/Headers/**", + "$(SRCROOT)/../node_modules/react-native-vector-icons/RNVectorIconsManager", + "$(SRCROOT)/../node_modules/react-native-simple-toast/ios/LRDRCTSimpleToast", + ); + INFOPLIST_FILE = ReactNativeFirebaseDemoTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "\"$(SRCROOT)/$(TARGET_NAME)\"", + "\"$(SRCROOT)/$(TARGET_NAME)\"", + ); + OTHER_LDFLAGS = ( + "-ObjC", + "-lc++", + ); + PRODUCT_NAME = "$(TARGET_NAME)"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/ReactNativeFirebaseDemo.app/ReactNativeFirebaseDemo"; + }; + name = Release; + }; + 13B07F941A680F5B00A75B9A /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 07C05CEFA32C3C442CA152DB /* Pods-ReactNativeFirebaseDemo.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CURRENT_PROJECT_VERSION = 1; + DEAD_CODE_STRIPPING = NO; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "$(SRCROOT)/../node_modules/react-native-firebase/Firebase.framework/Headers/**", + "$(SRCROOT)/../node_modules/react-native-vector-icons/RNVectorIconsManager", + "$(SRCROOT)/../node_modules/react-native-simple-toast/ios/LRDRCTSimpleToast", + ); + INFOPLIST_FILE = ReactNativeFirebaseDemo/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + OTHER_LDFLAGS = ( + "$(inherited)", + "-ObjC", + "-lc++", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.invertase.ReactNativeFirebaseDemo; + PRODUCT_NAME = ReactNativeFirebaseDemo; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 13B07F951A680F5B00A75B9A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 93FF19757985B70080544398 /* Pods-ReactNativeFirebaseDemo.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CURRENT_PROJECT_VERSION = 1; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "$(SRCROOT)/../node_modules/react-native-firebase/Firebase.framework/Headers/**", + "$(SRCROOT)/../node_modules/react-native-vector-icons/RNVectorIconsManager", + "$(SRCROOT)/../node_modules/react-native-simple-toast/ios/LRDRCTSimpleToast", + ); + INFOPLIST_FILE = ReactNativeFirebaseDemo/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + OTHER_LDFLAGS = ( + "$(inherited)", + "-ObjC", + "-lc++", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.invertase.ReactNativeFirebaseDemo; + PRODUCT_NAME = ReactNativeFirebaseDemo; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; + 2D02E4971E0B4A5E006451C7 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = "App Icon & Top Shelf Image"; + ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; + CLANG_ANALYZER_NONNULL = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_TESTABILITY = YES; + GCC_NO_COMMON_BLOCKS = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "$(SRCROOT)/../node_modules/react-native-firebase/Firebase.framework/Headers/**", + "$(SRCROOT)/../node_modules/react-native-vector-icons/RNVectorIconsManager", + "$(SRCROOT)/../node_modules/react-native-simple-toast/ios/LRDRCTSimpleToast", + ); + INFOPLIST_FILE = "ReactNativeFirebaseDemo-tvOS/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "\"$(SRCROOT)/$(TARGET_NAME)\"", + "\"$(SRCROOT)/$(TARGET_NAME)\"", + ); + OTHER_LDFLAGS = ( + "-ObjC", + "-lc++", + ); + PRODUCT_BUNDLE_IDENTIFIER = "com.facebook.REACT.ReactNativeFirebaseDemo-tvOS"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = appletvos; + TARGETED_DEVICE_FAMILY = 3; + TVOS_DEPLOYMENT_TARGET = 9.2; + }; + name = Debug; + }; + 2D02E4981E0B4A5E006451C7 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = "App Icon & Top Shelf Image"; + ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; + CLANG_ANALYZER_NONNULL = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + GCC_NO_COMMON_BLOCKS = YES; + HEADER_SEARCH_PATHS = ( + "$(inherited)", + "$(SRCROOT)/../node_modules/react-native-firebase/Firebase.framework/Headers/**", + "$(SRCROOT)/../node_modules/react-native-vector-icons/RNVectorIconsManager", + "$(SRCROOT)/../node_modules/react-native-simple-toast/ios/LRDRCTSimpleToast", + ); + INFOPLIST_FILE = "ReactNativeFirebaseDemo-tvOS/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "\"$(SRCROOT)/$(TARGET_NAME)\"", + "\"$(SRCROOT)/$(TARGET_NAME)\"", + ); + OTHER_LDFLAGS = ( + "-ObjC", + "-lc++", + ); + PRODUCT_BUNDLE_IDENTIFIER = "com.facebook.REACT.ReactNativeFirebaseDemo-tvOS"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = appletvos; + TARGETED_DEVICE_FAMILY = 3; + TVOS_DEPLOYMENT_TARGET = 9.2; + }; + name = Release; + }; + 2D02E4991E0B4A5E006451C7 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CLANG_ANALYZER_NONNULL = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_TESTABILITY = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "ReactNativeFirebaseDemo-tvOSTests/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "\"$(SRCROOT)/$(TARGET_NAME)\"", + "\"$(SRCROOT)/$(TARGET_NAME)\"", + ); + PRODUCT_BUNDLE_IDENTIFIER = "com.facebook.REACT.ReactNativeFirebaseDemo-tvOSTests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = appletvos; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/ReactNativeFirebaseDemo-tvOS.app/ReactNativeFirebaseDemo-tvOS"; + TVOS_DEPLOYMENT_TARGET = 10.1; + }; + name = Debug; + }; + 2D02E49A1E0B4A5E006451C7 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CLANG_ANALYZER_NONNULL = YES; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "ReactNativeFirebaseDemo-tvOSTests/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "\"$(SRCROOT)/$(TARGET_NAME)\"", + "\"$(SRCROOT)/$(TARGET_NAME)\"", + ); + PRODUCT_BUNDLE_IDENTIFIER = "com.facebook.REACT.ReactNativeFirebaseDemo-tvOSTests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = appletvos; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/ReactNativeFirebaseDemo-tvOS.app/ReactNativeFirebaseDemo-tvOS"; + TVOS_DEPLOYMENT_TARGET = 10.1; + }; + name = Release; + }; + 83CBBA201A601CBA00E9B192 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + }; + name = Debug; + }; + 83CBBA211A601CBA00E9B192 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget "ReactNativeFirebaseDemoTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 00E356F61AD99517003FC87E /* Debug */, + 00E356F71AD99517003FC87E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "ReactNativeFirebaseDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 13B07F941A680F5B00A75B9A /* Debug */, + 13B07F951A680F5B00A75B9A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2D02E4BA1E0B4A5E006451C7 /* Build configuration list for PBXNativeTarget "ReactNativeFirebaseDemo-tvOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2D02E4971E0B4A5E006451C7 /* Debug */, + 2D02E4981E0B4A5E006451C7 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2D02E4BB1E0B4A5E006451C7 /* Build configuration list for PBXNativeTarget "ReactNativeFirebaseDemo-tvOSTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2D02E4991E0B4A5E006451C7 /* Debug */, + 2D02E49A1E0B4A5E006451C7 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "ReactNativeFirebaseDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 83CBBA201A601CBA00E9B192 /* Debug */, + 83CBBA211A601CBA00E9B192 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */; +} diff --git a/tests/ios/ReactNativeFirebaseDemo.xcodeproj/xcshareddata/xcschemes/ReactNativeFirebaseDemo-tvOS.xcscheme b/tests/ios/ReactNativeFirebaseDemo.xcodeproj/xcshareddata/xcschemes/ReactNativeFirebaseDemo-tvOS.xcscheme new file mode 100644 index 00000000..a5e39259 --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemo.xcodeproj/xcshareddata/xcschemes/ReactNativeFirebaseDemo-tvOS.xcscheme @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/ios/ReactNativeFirebaseDemo.xcodeproj/xcshareddata/xcschemes/ReactNativeFirebaseDemo.xcscheme b/tests/ios/ReactNativeFirebaseDemo.xcodeproj/xcshareddata/xcschemes/ReactNativeFirebaseDemo.xcscheme new file mode 100644 index 00000000..8ae9caf0 --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemo.xcodeproj/xcshareddata/xcschemes/ReactNativeFirebaseDemo.xcscheme @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/ios/ReactNativeFirebaseDemo/AppDelegate.h b/tests/ios/ReactNativeFirebaseDemo/AppDelegate.h new file mode 100644 index 00000000..a9654d5e --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemo/AppDelegate.h @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +@interface AppDelegate : UIResponder + +@property (nonatomic, strong) UIWindow *window; + +@end diff --git a/tests/ios/ReactNativeFirebaseDemo/AppDelegate.m b/tests/ios/ReactNativeFirebaseDemo/AppDelegate.m new file mode 100644 index 00000000..b7f877eb --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemo/AppDelegate.m @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +#import "AppDelegate.h" + +#import +#import +#import + +@implementation AppDelegate + +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ + [FIRApp configure]; + NSURL *jsCodeLocation; + jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil]; + + RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation + moduleName:@"ReactNativeFirebaseDemo" + initialProperties:nil + launchOptions:launchOptions]; + + rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; + + self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; + UIViewController *rootViewController = [UIViewController new]; + rootViewController.view = rootView; + self.window.rootViewController = rootViewController; + [self.window makeKeyAndVisible]; + return YES; +} + +@end diff --git a/tests/ios/ReactNativeFirebaseDemo/Base.lproj/LaunchScreen.xib b/tests/ios/ReactNativeFirebaseDemo/Base.lproj/LaunchScreen.xib new file mode 100644 index 00000000..5b5d75aa --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemo/Base.lproj/LaunchScreen.xib @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Contents.json b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000..905c43e5 --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,74 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-29.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-40@3x.png", + "scale" : "3x" + }, + { + "size" : "57x57", + "idiom" : "iphone", + "filename" : "Icon-57.png", + "scale" : "1x" + }, + { + "size" : "57x57", + "idiom" : "iphone", + "filename" : "Icon-57@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-60@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-20@2x.png b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-20@2x.png new file mode 100644 index 00000000..e938ca7c Binary files /dev/null and b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-20@2x.png differ diff --git a/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-20@3x.png b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-20@3x.png new file mode 100644 index 00000000..b7039274 Binary files /dev/null and b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-20@3x.png differ diff --git a/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-29.png b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-29.png new file mode 100644 index 00000000..6a25ce2a Binary files /dev/null and b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-29.png differ diff --git a/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-29@2x.png b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-29@2x.png new file mode 100644 index 00000000..c5ac5f43 Binary files /dev/null and b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-29@2x.png differ diff --git a/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-29@3x.png b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-29@3x.png new file mode 100644 index 00000000..e34df1ad Binary files /dev/null and b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-29@3x.png differ diff --git a/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-40@2x.png b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-40@2x.png new file mode 100644 index 00000000..eaae497a Binary files /dev/null and b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-40@2x.png differ diff --git a/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-40@3x.png b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-40@3x.png new file mode 100644 index 00000000..280cedd5 Binary files /dev/null and b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-40@3x.png differ diff --git a/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-57.png b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-57.png new file mode 100644 index 00000000..1af5e11a Binary files /dev/null and b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-57.png differ diff --git a/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-57@2x.png b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-57@2x.png new file mode 100644 index 00000000..302d009f Binary files /dev/null and b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-57@2x.png differ diff --git a/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-60@2x.png b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-60@2x.png new file mode 100644 index 00000000..280cedd5 Binary files /dev/null and b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-60@2x.png differ diff --git a/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-60@3x.png b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-60@3x.png new file mode 100644 index 00000000..9f3e797e Binary files /dev/null and b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/AppIcon.appiconset/Icon-60@3x.png differ diff --git a/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/Contents.json b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/Contents.json new file mode 100644 index 00000000..da4a164c --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemo/Images.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/tests/ios/ReactNativeFirebaseDemo/Info.plist b/tests/ios/ReactNativeFirebaseDemo/Info.plist new file mode 100644 index 00000000..f764dd7f --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemo/Info.plist @@ -0,0 +1,66 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSRequiresIPhoneOS + + NSAppTransportSecurity + + NSExceptionDomains + + localhost + + NSExceptionAllowsInsecureHTTPLoads + + + + + NSLocationWhenInUseUsageDescription + + UIAppFonts + + Entypo.ttf + EvilIcons.ttf + FontAwesome.ttf + Foundation.ttf + Ionicons.ttf + MaterialCommunityIcons.ttf + MaterialIcons.ttf + Octicons.ttf + SimpleLineIcons.ttf + Zocial.ttf + + UILaunchStoryboardName + LaunchScreen + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIViewControllerBasedStatusBarAppearance + + + diff --git a/tests/ios/ReactNativeFirebaseDemo/main.m b/tests/ios/ReactNativeFirebaseDemo/main.m new file mode 100644 index 00000000..3d767fcb --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemo/main.m @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +#import + +#import "AppDelegate.h" + +int main(int argc, char * argv[]) { + @autoreleasepool { + return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); + } +} diff --git a/tests/ios/ReactNativeFirebaseDemoTests/Info.plist b/tests/ios/ReactNativeFirebaseDemoTests/Info.plist new file mode 100644 index 00000000..886825cc --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemoTests/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/tests/ios/ReactNativeFirebaseDemoTests/ReactNativeFirebaseDemoTests.m b/tests/ios/ReactNativeFirebaseDemoTests/ReactNativeFirebaseDemoTests.m new file mode 100644 index 00000000..fd9d570c --- /dev/null +++ b/tests/ios/ReactNativeFirebaseDemoTests/ReactNativeFirebaseDemoTests.m @@ -0,0 +1,70 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +#import +#import + +#import +#import + +#define TIMEOUT_SECONDS 600 +#define TEXT_TO_LOOK_FOR @"Welcome to React Native!" + +@interface ReactNativeFirebaseDemoTests : XCTestCase + +@end + +@implementation ReactNativeFirebaseDemoTests + +- (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test +{ + if (test(view)) { + return YES; + } + for (UIView *subview in [view subviews]) { + if ([self findSubviewInView:subview matching:test]) { + return YES; + } + } + return NO; +} + +- (void)testRendersWelcomeScreen +{ + UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController]; + NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS]; + BOOL foundElement = NO; + + __block NSString *redboxError = nil; + RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) { + if (level >= RCTLogLevelError) { + redboxError = message; + } + }); + + while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) { + [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; + [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; + + foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) { + if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) { + return YES; + } + return NO; + }]; + } + + RCTSetLogFunction(RCTDefaultLogFunction); + + XCTAssertNil(redboxError, @"RedBox error: %@", redboxError); + XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS); +} + + +@end diff --git a/tests/lib/RunStatus.js b/tests/lib/RunStatus.js new file mode 100644 index 00000000..daf27d52 --- /dev/null +++ b/tests/lib/RunStatus.js @@ -0,0 +1,5 @@ +module.exports = { + RUNNING: 'running', + OK: 'success', + ERR: 'error', +}; diff --git a/tests/lib/TestDSL.js b/tests/lib/TestDSL.js new file mode 100644 index 00000000..bbdd5502 --- /dev/null +++ b/tests/lib/TestDSL.js @@ -0,0 +1,251 @@ +/** + * Class that provides DSL for declaratively defining tests. Provides a declarative + * interface for {@link TestSuiteDefinition} and only reveals methods that are part + * of the test definition DSL. + */ +class TestDSL { + /** + * Create a new instance of TestDSL + * @param {TestSuiteDefinition} testSuiteDefinition - Class to delegate the heavy lifting + * of satisfying the DSL, to. + * @param {Object} firebase - Object containing native and web firebase instances + * @param {Object} firebase.native - Native firebase instance + * @para {Object} firebase.web - Web firebase instance + */ + constructor(testSuiteDefinition, firebase) { + this._testSuiteDefinition = testSuiteDefinition; + + this.firebase = firebase; + + this.after = this.after.bind(this); + this.afterEach = this.afterEach.bind(this); + + this.before = this.before.bind(this); + this.beforeEach = this.beforeEach.bind(this); + + this.describe = this.describe.bind(this); + /** Alias for {@link TestDSL#describe } */ + this.context = this.describe; + this.fdescribe = this.fdescribe.bind(this); + /** Alias for {@link TestDSL#fdescribe } */ + this.fcontext = this.fdescribe; + this.xdescribe = this.xdescribe.bind(this); + /** Alias for {@link TestDSL#xdescribe } */ + this.xcontext = this.xdescribe; + + this.tryCatch = this.tryCatch.bind(this); + + this.it = this.it.bind(this); + this.xit = this.xit.bind(this); + this.fit = this.fit.bind(this); + } + + /** + * Add a function as a before hook to the current test context + * @param {Object=} options - Options object + * @param {Number=10000} options.timeout - Number of milliseconds before callback times + * out + * @param {Function} callback - Function to add as before hook to current test context + */ + before(options, callback = undefined) { + const _options = callback ? options : {}; + const _callback = callback || options; + + this._testSuiteDefinition.addBeforeHook(_callback, _options); + } + + /** + * Add a function as a before each hook to the current test context + * @param {Object=} options - Options object + * @param {Number=10000} options.timeout - Number of milliseconds before callback times + * out + * @param {Function} callback - Function to add as before each hook to current test + * context + */ + beforeEach(options, callback = undefined) { + const _options = callback ? options : {}; + const _callback = callback || options; + + this._testSuiteDefinition.addBeforeEachHook(_callback, _options); + } + + /** + * Add a function as a after each hook to the current test context + * @param {Object=} options - Options object + * @param {Number=10000} options.timeout - Number of milliseconds before callback times + * out + * @param {Function} callback - Function to add as after each hook to current test context + */ + afterEach(options, callback = undefined) { + const _options = callback ? options : {}; + const _callback = callback || options; + + this._testSuiteDefinition.addAfterEachHook(_callback, _options); + } + + /** + * Add a function as a after hook to the current test context + * @param {Object=} options - Options object + * @param {Number=10000} options.timeout - Number of milliseconds before callback times + * out + * @param {Function} callback - Function to add as after hook to current test context + */ + after(options, callback = undefined) { + const _options = callback ? options : {}; + const _callback = callback || options; + + this._testSuiteDefinition.addAfterHook(_callback, _options); + } + + /** + * Starts a new test context + * @param {String} name - name of new test context + * @param {ContextOptions} options - options for context + * @param {Function} [testDefinitions={}] - function that defines further test contexts and + * tests using the test DSL + */ + describe(name, options, testDefinitions) { + let _testDefinitions; + let _options; + + if (testDefinitions) { + _testDefinitions = testDefinitions; + _options = options; + } else { + _testDefinitions = options; + _options = {}; + } + + this._testSuiteDefinition.pushTestContext(name, _options); + _testDefinitions(); + this._testSuiteDefinition.popTestContext(); + } + + /** + * Starts a new pending test context. Tests in a pending test context are not + * run when the test suite is executed. They also appear greyed out. + * @param {String} name - name of new test context + * @param {ContextOptions} [options={}] - options for context + * @param {Function} testDefinitions - function that defines further test contexts and + * tests using the test DSL + */ + xdescribe(name, options, testDefinitions = undefined) { + let _options = {}; + let _testDefinitions; + + if (typeof options === 'function') { + _options = { pending: true }; + _testDefinitions = options; + } else { + Object.assign(_options, options, { pending: true }); + _testDefinitions = testDefinitions; + } + + this.describe(name, _options, _testDefinitions); + } + + /** + * Starts a new focused test context. Tests in a focused test context are the only + * ones that appear and are run when the test suite is executed. + * @param {String} name - name of new test context + * @param {ContextOptions} [options={}] - options for context + * @param {Function} testDefinitions - function that defines further test contexts and + * tests using the test DSL + */ + fdescribe(name, options, testDefinitions = undefined) { + let _options = {}; + let _testDefinitions; + + if (typeof options === 'function') { + _options = { focus: true }; + _testDefinitions = options; + } else { + Object.assign(_options, options, { focus: true }); + _testDefinitions = testDefinitions; + } + + this.describe(name, _options, _testDefinitions); + } + + /** + * Defines a new test. + * @param {String} description - Brief description of what the test expects + * @param {TestOptions} options - Options of whether test should be focused or pending + * @param {Function} testFunction - Body of the test containing setup and assertions + */ + it(description, options, testFunction = undefined) { + this._testSuiteDefinition.addTest(description, options, testFunction); + } + + /** + * Defines a new pending test. Pending tests are not run when the test suite is + * executed. They also appear greyed out. + * @param {String} description - Brief description of what the test expects + * @param {ContextOptions} [options={}] - Options of whether test should be focused or pending + * @param {Function} testFunction - Body of the test containing setup and assertions + */ + xit(description, options, testFunction = undefined) { + let _options = {}; + let _testFunction; + + if (typeof options === 'function') { + _options = { pending: true }; + _testFunction = options; + } else { + Object.assign(_options, options, { pending: true }); + _testFunction = testFunction; + } + + this.it(description, _options, _testFunction); + } + + + /** + * Defines a new focused test. Focused tests are the only + * ones that appear and are run when the test suite is executed. + * @param {String} description - Brief description of what the test expects + * @param {ContextOptions} [options={}] - Options of whether test should be focused or pending + * @param {Function} testFunction - Body of the test containing setup and assertions + */ + fit(description, options, testFunction = undefined) { + let _options = {}; + let _testFunction; + + if (typeof options === 'function') { + _options = { focus: true }; + _testFunction = options; + } else { + Object.assign(_options, options, { focus: true }); + _testFunction = testFunction; + } + + this.it(description, _options, _testFunction); + } + + /** + * Tries evaluating a function and calls a reject callback if it throws an error + * @param {Function} callback - Function to evaluate + * @param {Function} reject - Function to call if callback throws an error + * @returns {function(...[*])} a function that will catch any errors thrown by callback, + * passing them to reject instead. + */ + tryCatch(callback, reject) { + return (...args) => { + try { + callback(...args); + } catch (error) { + reject(error); + } + }; + } +} + +/** + * Log a test DSL error to the console. + * @param {String} error - Message to included in message logged to the console + */ +function testDSLError(error) { + console.error(`ReactNativeFirebaseTests.TestDSLError: ${error}`); + console.error('This test was ignored.'); +} +export default TestDSL; diff --git a/tests/lib/TestRun.js b/tests/lib/TestRun.js new file mode 100644 index 00000000..c927949d --- /dev/null +++ b/tests/lib/TestRun.js @@ -0,0 +1,386 @@ +import Promise from 'bluebird'; +import RunStatus from './RunStatus'; + +const EVENTS = { + TEST_SUITE_STATUS: 'TEST_SUITE_STATUS', + TEST_STATUS: 'TEST_STATUS', +}; + +/** + * Class that encapsulates synchronously running a suite's tests. + */ +class TestRun { + /** + * The number of tests that have been executed so far + * @type {number} + */ + completedTests = 0; + + /** + * Creates a new TestRun + * @param {TestSuite} testSuite - Test suite that tests belong to + * @param {Test[]} tests - List of test to run + * @param {TestSuiteDefinition} testDefinitions - Definition of tests and contexts + */ + constructor(testSuite, tests, testDefinitions) { + this.testSuite = testSuite; + + this.tests = tests; + + this.rootContextId = testDefinitions.rootTestContextId; + + this.testContexts = tests.reduce((memo, test) => { + const testContextId = test.testContextId; + + this._recursivelyAddContextsTo(memo, testContextId, testDefinitions.testContexts); + + memo[testContextId].tests.unshift(test); + + return memo; + }, {}); + + this.listeners = { + [EVENTS.TEST_STATUS]: [], + [EVENTS.TEST_SUITE_STATUS]: [], + }; + } + + /** + * Registers a listener for a change event + * @param {String} action - one of the actions in EVENTS + * @param {Function} callback - Callback that accepts event object + */ + onChange(action, callback) { + this.listeners[action].push(callback); + } + + /** + * Walks up a context tree, copying test contexts from a source object to a target one. + * Used for ensuring all of a test's parent contexts are added to the target object. + * @param {Object} target - Object to put test contexts in + * @param {Number} id - Id of current context to add to target + * @param {Object} source - Object to get complete list of test contexts + * from. + * @param {Number} childContextId - id of child of current context + * @private + */ + _recursivelyAddContextsTo(target, id, source, childContextId = null) { + const testContext = source[id]; + + if (!target[id]) { + // eslint-disable-next-line no-param-reassign + target[id] = { + ...testContext, + tests: [], + childContextIds: {}, + }; + } + + if (childContextId) { + // eslint-disable-next-line no-param-reassign + target[id].childContextIds[childContextId] = true; + } + + const parentContextId = testContext.parentContextId; + + if (parentContextId) { + this._recursivelyAddContextsTo(target, parentContextId, source, id); + } + } + + _updateStatus(action, values) { + const listeners = this.listeners[action]; + + listeners.forEach(listener => listener(values)); + } + + /** + * Execute the tests TestRun was initialised with. + * @returns {Promise.} Resolves once all the tests in the test suite have + * completed running. + */ + async execute() { + const store = this.testSuite.reduxStore; + + if (!store) { + testRuntimeError(`Failed to run ${this.testSuite.name} tests as no Redux store has been provided`); + } + + this._updateStatus(EVENTS.TEST_SUITE_STATUS, { + suiteId: this.testSuite.id, + status: RunStatus.RUNNING, + + progress: 0, + time: 0, + }); + + // Start timing + + this.runStartTime = Date.now(); + + const rootContext = this.testContexts[this.rootContextId]; + + if (rootContext) { + await this._runTestsInContext(rootContext); + + const errors = this.tests.filter(test => test.status === RunStatus.ERR); + + if (errors.length) { + this._updateStatus(EVENTS.TEST_SUITE_STATUS, { + suiteId: this.testSuite.id, + status: RunStatus.ERR, + progress: 100, + + time: Date.now() - this.runStartTime, + message: `${errors.length} test${errors.length > 1 ? 's' : ''} has error(s).`, + }); + } else { + this._updateStatus(EVENTS.TEST_SUITE_STATUS, ({ + suiteId: this.testSuite.id, + status: RunStatus.OK, + progress: 100, + + time: Date.now() - this.runStartTime, + message: '', + })); + } + } + } + + /** + * Recursively enter a test context and run its before, beforeEach hooks where + * appropriate; execute the test and then run afterEach and after hooks where + * appropriate. + * @param {TestContext} testContext - context to run hooks for + * @param {Function[][]} beforeEachHooks - stack of beforeEach hooks defined + * in parent contexts that should be run beforeEach test in child contexts + * @param {Function[][]} afterEachHooks - stack of afterEach hooks defined + * in parent contexts that should be run afterEach test in child contexts + * @returns {Promise.} Resolves once all tests and their hooks have run + * @private + */ + async _runTestsInContext(testContext, beforeEachHooks = [], afterEachHooks = []) { + const beforeHookRan = await this._runContextHooks(testContext, 'before'); + + if (beforeHookRan) { + beforeEachHooks.push(testContext.beforeEachHooks || []); + afterEachHooks.unshift(testContext.afterEachHooks || []); + + await this._runTests(testContext, testContext.tests, flatten(beforeEachHooks), flatten(afterEachHooks)); + + await Promise.each(Object.keys(testContext.childContextIds), (childContextId) => { + const childContext = this.testContexts[childContextId]; + return this._runTestsInContext(childContext, beforeEachHooks, afterEachHooks); + }); + + beforeEachHooks.pop(); + afterEachHooks.shift(); + + await this._runContextHooks(testContext, 'after'); + } + } + + /** + * Synchronously run hooks in context's (before|after) hooks, starting from the first + * hook + * @param {TestContext} testContext - context containing hooks + * @param {('before'|'after')} hookName - name of hooks to run callbacks for + * @returns {Promise.<*>} Resolves when last hook in list has been executed + * @private + */ + async _runContextHooks(testContext, hookName) { + const hooks = testContext[`${hookName}Hooks`] || []; + + return this._runHookChain(null, Date.now(), testContext, hookName, hooks); + } + + _runHookChain(test, testStart, testContext, hookName, hooks) { + return Promise.each(hooks, async (hook) => { + const error = await this._safelyRunFunction(hook.callback, hook.timeout, `${hookName} hook`); + + if (error) { + const errorPrefix = `Error occurred in "${testContext.name}" ${hookName} Hook: `; + + if (test) { + this._reportTestError(test, error, Date.now() - testStart, errorPrefix); + } else { + this._reportAllTestsAsFailed(testContext, error, testStart, errorPrefix); + } + + throw new Error(); + } + }).then(() => true).catch(() => false); + } + + _reportAllTestsAsFailed(testContext, error, testStart, errorPrefix) { + testContext.tests.forEach((test) => { + this._reportTestError(test, error, Date.now() - testStart, errorPrefix); + }); + + testContext.childContextIds.forEach((contextId) => { + this._reportAllTestsAsFailed(this.testContext[contextId], error, testStart, errorPrefix); + }); + } + + /** + * Synchronously run a list of tests + * @param {TestContext} testContext - Test context to run beforeEach and AfterEach hooks + * for + * @param {Test[]} tests - List of tests to run + * @param {Function[]} beforeEachHooks - list of functions to run before each test + * @param {Function[]} afterEachHooks - list of functions to run after each test + * @returns {Promise.} - Resolves once all tests and their afterEach hooks have + * been run + * @private + */ + async _runTests(testContext, tests, beforeEachHooks, afterEachHooks) { + return Promise.each(tests, async (test) => { + this._updateStatus(EVENTS.TEST_STATUS, { + testId: test.id, + status: RunStatus.RUNNING, + time: 0, + message: '', + }); + + const testStart = Date.now(); + + const beforeEachRan = await this._runHookChain(test, testStart, testContext, 'beforeEach', beforeEachHooks); + + if (beforeEachRan) { + const error = await this._safelyRunFunction(test.func.bind(null, [test, this.testSuite.reduxStore.getState()]), test.timeout, 'Test'); + + // Update test status + + if (error) { + this._reportTestError(test, error, Date.now() - testStart); + } else { + // eslint-disable-next-line no-param-reassign + test.status = RunStatus.OK; + + this._updateStatus(EVENTS.TEST_STATUS, { + testId: test.id, + status: RunStatus.OK, + time: Date.now() - testStart, + message: '', + }); + } + + // Update suite progress + + this.completedTests += 1; + + this._updateStatus(EVENTS.TEST_SUITE_STATUS, { + suiteId: this.testSuite.id, + status: RunStatus.RUNNING, + progress: (this.completedTests / this.tests.length) * 100, + time: Date.now() - this.runStartTime, + message: '', + }); + + await this._runHookChain(test, testStart, testContext, 'afterEach', afterEachHooks); + } + }) + + .catch((error) => { + this._updateStatus(EVENTS.TEST_SUITE_STATUS, { + suiteId: this.testSuite.id, + status: RunStatus.ERR, + time: Date.now() - this.runStartTime, + message: `Test suite failed: ${error.message}`, + stackTrace: error.stack, + }); + }); + } + + _reportTestError(test, error, time, errorPrefix = '') { + // eslint-disable-next-line no-param-reassign + test.status = RunStatus.ERR; + + this._updateStatus(EVENTS.TEST_STATUS, { + testId: test.id, + status: RunStatus.ERR, + time, + message: `${errorPrefix}${error.message ? `${error.name}: ${error.message}` : error}`, + stackTrace: error.stack, + }); + } + + async _safelyRunFunction(func, timeOutDuration, description) { + const syncResultOrPromise = tryCatcher(func); + + if (syncResultOrPromise.error) { + // Synchronous Error + return syncResultOrPromise.error; + } + + // Asynchronous Error + return promiseToCallBack(syncResultOrPromise.value, timeOutDuration, description); + } + +} + +/** + * Try catch to object + * @returns {{}} + * @private + */ + +function tryCatcher(func) { + const result = {}; + + try { + result.value = func(); + } catch (e) { + result.error = e; + } + + return result; +} + +/** + * Make a promise callback-able to trap errors + * @param promise + * @private + */ + +function promiseToCallBack(promise, timeoutDuration, description) { + let returnValue = null; + + try { + returnValue = Promise.resolve(promise) + .then(() => { + return null; + }, (error) => { + return Promise.resolve(error); + }) + .timeout(timeoutDuration, `${description} took longer than ${timeoutDuration}ms. This can be extended with the timeout option.`) + .catch((error) => { + return Promise.resolve(error); + }); + } catch (error) { + returnValue = Promise.resolve(error); + } + + return returnValue; +} + +/** + * Flatten a two dimensional array to a single dimensional array + * @param {*[]} list - two dimensional array + * @returns {*[]} One-dimensional array + */ +function flatten(list) { + return list.reduce((memo, contextHooks) => { + return memo.concat(contextHooks); + }, []); +} + +/** + * Log a runtime error to the console + * @param {String} error - Message to log to the console + */ +function testRuntimeError(error) { + console.error(`ReactNativeFirebaseTests.TestRuntimeError: ${error}`); +} + +export default TestRun; diff --git a/tests/lib/TestSuite.js b/tests/lib/TestSuite.js new file mode 100644 index 00000000..3924bb8b --- /dev/null +++ b/tests/lib/TestSuite.js @@ -0,0 +1,148 @@ +import 'should'; +import 'should-sinon'; + +import TestSuiteDefinition from './TestSuiteDefinition'; +import TestRun from './TestRun'; + +/** + * Incrementing counter to assign each test suite a globally unique id. Should be + * accessed only through assignTestSuiteId + * @type {number} Counter that maintains globally unique id and increments each time + * a new id is assigned + */ +let testSuiteCounter = 0; + +/** + * Increment the testSuiteCounter and return the new value. Used + * for assigning a new globally unique id to a test suite. + * @returns {number} globally unique id assigned to each test suite + */ +function assignTestSuiteId() { + testSuiteCounter += 1; + return testSuiteCounter; +} + +/** + * Class that provides imperative interface for constructing and running a test suite. + * Used for instantiating a new test suite, adding tests to it and then running all or + * a subset of those tests. + * + * @example + * // Creates a new test suite + * const testSuit = new TestSuite('Feature Group A', 'Feature a, b and c'); + */ +class TestSuite { + /** + * Creates a new test suite. + * @param {String} name - The name of the test suite + * @param {String} description - A short description of the test suite + * @param {Object} firebase - Object containing native and web firebase instances + * @param {Object} firebase.native - Native firebase instance + * @para {Object} firebase.web - Web firebase instance + */ + constructor(name, description, firebase) { + this.id = assignTestSuiteId(); + this.name = name; + this.description = description; + + this.reduxStore = null; + this.testDefinitions = new TestSuiteDefinition(this, firebase); + } + + /** + * @typedef {Function} TestDefinitionFunction + * @param {TestDSL} testDSL - class instance that defines the testing DSL that can + * be used in defining tests + */ + + /** + * Adds tests defined in a function to the test suite + * @param {TestDefinitionFunction} testDefinition - A function that defines one or + * more test suites using the test DSL. + * @example + * // Adding tests + * const testDefinition = function({ describe, it }) { + * describe('Some context', () => { + * it('then does something', () => { + * // Test assertions here + * }) + * }) + * testSuite.addTests(testDefinition); + */ + addTests(testDefinition) { + testDefinition(this.testDefinitions.DSL); + } + + /** + * @typedef {Object} ReduxStore + * @property {Function} getState - Returns the current state of the store + * @property {Function} dispatch - Dispatches a new action to update to store + */ + + /** + * Sets the redux store assigned to the test suite + * @param {ReduxStore} store - The redux store to add to the test suite + * @param {Function} testSuiteAction - Function that accepts an object of + * event values and returns another that is suitable to dispatch to the + * redux store. Responsible for handling events when the test suite's status + * has changed. + * @param {Function} testAction - Function that accepts an object of + * event values and returns another that is suitable to dispatch to the + * redux store. Responsible for handling events when a test's status + * has changed. + */ + setStore(store, testSuiteAction, testAction) { + this.reduxStore = store; + this.suiteChangHandler = testSuiteAction; + this.testChangHandler = testAction; + } + + /** + * Run all the tests matching an array of ids. If the array is not provided, run all + * test in the test suite. + * @param {number[]=} testIds - array of ids for tests to run + * @throws {RangeError} testIds must correspond with tests in the test suite + * @example + * // Running all tests in the test suite + * testSuite.run(); + * @example + * // Run only tests with id 1 and 2 + * testSuite.run([1, 2]); + */ + async run(testIds = undefined) { + const testsToRun = (() => { + if (testIds) { + return testIds.map((id) => { + const test = this.testDefinitions.tests[id]; + + if (!test) { + throw new RangeError(`ReactNativeFirebaseTests.TestRunError: Test with id ${id} not found in test suite ${this.name}`); + } + + return test; + }); + } + + return Object.values(this.testDefinitions.tests); + })(); + + const testRun = new TestRun(this, testsToRun.reverse(), this.testDefinitions); + + testRun.onChange('TEST_SUITE_STATUS', (values) => { + if (this.suiteChangHandler) { + this.suiteChangHandler(values); + } + }); + + testRun.onChange('TEST_STATUS', (values) => { + if (this.testChangHandler) { + this.testChangHandler(values); + } + }); + + await testRun.execute(); + } + +} + +export default TestSuite; diff --git a/tests/lib/TestSuiteDefinition.js b/tests/lib/TestSuiteDefinition.js new file mode 100644 index 00000000..1ebc9aea --- /dev/null +++ b/tests/lib/TestSuiteDefinition.js @@ -0,0 +1,360 @@ +import TestDSL from './TestDSL'; + +/** + * Incrementing counter to assign each test context a globally unique id. + * @type {number} Counter that maintains globally unique id and increments each time + * a new id is assigned + */ +let testContextCounter = 0; + +/** + * Incrementing counter to assign each test a globally unique id. + * @type {number} Counter that maintains globally unique id and increments each time + * a new id is assigned + */ +let testCounter = 0; + +/** + * Increment the testCounter and return the new value. Used + * for assigning a new globally unique id to a test. + * @returns {number} globally unique id assigned to each test + */ +function assignTestId() { + testCounter += 1; + return testCounter; +} + +/** + * Increment the testContextCounter and return the new value. Used + * for assigning a new globally unique id to a test context. + * @returns {number} globally unique id assigned to each test context + */ +function assignContextId() { + testContextCounter += 1; + return testContextCounter; +} + +/** + * Enum for operators that can be used when combining test properties with their + * parents at definition time. + * @readonly + * @enum {String} ContextOperator + */ +const CONTEXT_OPERATORS = { + /** Perform OR of test value with context chain values **/ + OR: 'OR', +}; + +/** + * Class that provides imperative interface for defining tests. When defining tests + * the declarative interface for this class, {@link TestDSL} should be use instead. + */ +class TestSuiteDefinition { + /** + * Creates a new TestSuiteDefinition + * @param {TestSuite} testSuite - The {@link TestSuite} instance for which to + * define tests for. + * @param {Object} firebase - Object containing native and web firebase instances + * @param {Object} firebase.native - Native firebase instance + * @para {Object} firebase.web - Web firebase instance + */ + constructor(testSuite, firebase) { + this.testSuite = testSuite; + + this.tests = {}; + this.pendingTestIds = {}; + this.focusedTestIds = {}; + + this.testContexts = {}; + + this.rootTestContextId = assignContextId(); + this.rootTestContext = this._initialiseContext(this.rootTestContextId, { + name: '', + focus: false, + pending: false, + parentContextId: null, + }); + + this.currentTestContext = this.rootTestContext; + + this._testDSL = new TestDSL(this, firebase); + } + + /** + * Get the instance of {@link TestDSL} used for declaratively defining tests + * @returns {TestDSL} The TestDSL used for defining tests + */ + get DSL() { + return this._testDSL; + } + + /** + * Add a function as a before hook to the current test context + * @param {Function} callback - Function to add as before hook to current test context + */ + addBeforeHook(callback, options = {}) { + this._addHook('before', callback, options); + } + + /** + * Add a function as a before each hook to the current test context + * @param {Function} callback - Function to add as before each hook to current test + * context + */ + addBeforeEachHook(callback, options = {}) { + this._addHook('beforeEach', callback, options); + } + + /** + * Add a function as a after each hook to the current test context + * @param {Function} callback - Function to add as after each hook to current test context + */ + addAfterEachHook(callback, options = {}) { + this._addHook('afterEach', callback, options); + } + + /** + * Add a function as a after hook to the current test context + * @param {Function} callback - Function to add as after hook to current test context + */ + addAfterHook(callback, options = {}) { + this._addHook('after', callback, options); + } + + /** + * Add a function to the list of hooks matching hookName, for the current test context + * @param {('before'|'beforeEach'|'afterEach'|'after')} hookName - The name of the hook to add the function to + * @param {Function} callback - Function to add as a hook + * @param {Object=} options - Hook configuration options + * @private + */ + _addHook(hookName, callback, options = {}) { + const hookAttribute = `${hookName}Hooks`; + + if (callback && typeof callback === 'function') { + this.currentTestContext[hookAttribute] = this.currentTestContext[hookAttribute] || []; + this.currentTestContext[hookAttribute].push({ + callback, + timeout: options.timeout || 5000, + }); + } else { + testDefinitionError(`non-function value ${callback} passed to ${hookName} for '${this.currentTestContext.name}'`); + } + } + + /** + * @typedef {Object} ContextOptions + * @property {Boolean} [focused=undefined] - whether context is focused or not. + * @property {Boolean} [pending=undefined] - whether context is pending or not. + */ + + /** + * @typedef {Object} TestOptions + * @extends ContextOptions + * @property {Number} [timeout=5000] - Number of milliseconds before test times out + */ + + /** + * Push a test context onto the context stack, making it the new current test context + * @param {String} name - The name of the new context + * @param {ContextOptions} options - Options for new context + */ + pushTestContext(name, options = {}) { + const testContextId = assignContextId(); + const parentContext = this.currentTestContext; + this.currentTestContext = this._initialiseContext(testContextId, Object.assign({ name, parentContextId: parentContext.id }, options)); + } + + /** + * Pop test context off the context stack, making the previous context the new + * current context. + */ + popTestContext() { + const parentContextId = this.currentTestContext.parentContextId; + this.currentTestContext = this.testContexts[parentContextId]; + } + + /** + * Add a test to the current test context + * @param {String} description - The new test's description + * @param {ContextOptions} options - The options for the new test + * @param {Function} testFunction - The function that comprises the test's body + */ + addTest(description, options, testFunction = undefined) { + let _testFunction; + let _options; + + if (testFunction) { + _testFunction = testFunction; + _options = options; + } else { + _testFunction = options; + _options = {}; + } + + if (_testFunction && typeof _testFunction === 'function') { + // Create test + const testId = assignTestId(); + + this._createTest(testId, { + testContextId: this.currentTestContext.id, + testSuiteId: this.testSuite.id, + description: this._testDescriptionContextPrefix(this.currentTestContext) + description, + func: _testFunction, + timeout: _options.timeout || 5000, + }); + + // Add tests to context + this.currentTestContext.testIds.push(testId); + + if (_options.focus || this.currentTestContext.focus) { + this.focusedTestIds[testId] = true; + } + + if (_options.pending || this.currentTestContext.pending) { + this.pendingTestIds[testId] = true; + } + } else { + testDefinitionError(`Invalid test function for "${description}".`); + } + } + + /** + * Get the prefix to prepend to a test to fully describe it. Any context that is + * nested 2 or more deep, i.e. non the root context nor a child of the root context, + * has its name recursively prepended to all tests in that context or contexts it + * contains. This allows tests to be easily displayed in a LinkedList during viewing + * and reporting the test suite. + * @param {Object} contextProperties - Properties of current context + * @param {Number} contextProperties.id - Id of context + * @param {String} contextProperties.name - Name of context + * @param {Number} contextProperties.parentContextId - Id of context's parent + * @param {String} [suffix=''] - Accumulation of context prefixes so far. Starts empty + * and collects context prefixes as it recursively calls itself to iterate up the + * context tree. + * @returns {String} Prefix to be prepended to current accumulative string of context + * names + * @private + */ + _testDescriptionContextPrefix({ id, name, parentContextId }, suffix = '') { + if (id === this.rootTestContextId || parentContextId === this.rootTestContextId) { + return suffix; + } + + return this._testDescriptionContextPrefix(this.testContexts[parentContextId], `${name} ${suffix}`); + } + + /** + * @typedef {Object} TestContext + * @property {Number} id - Globally unique id + * @property {String} name - Short description of context + * @property {Boolean} [focus=false] - Whether context is focused + * @property {Boolean} [pending=false] - Whether context is pending + * @property {Number} [parentContextId=undefined] - Id of context that contains the current one + * @property {Number[]} testIds - List of ids of tests to be run in current context + * @property {Number} testSuiteId - Id of test suite test context is apart of + */ + + /** + * Create a context from options provided + * @param {Number} testContextId - Id to assign to new context once it's created + * @param {Object} options - options to use to create the context + * @param {String} options.name - Name of context to create + * @param {Boolean} options.focus - Whether context is focused or not + * @param {Boolean} options.pending - Whether context is pending or not + * @param {Number} [options.parentContextId=undefined] - Id of context's parent + * @returns {TestContext} New test context once it has been initialised + * @private + */ + _initialiseContext(testContextId, { name, focus, pending, parentContextId }) { + const existingContext = this.testContexts[testContextId]; + + if (existingContext) { + return existingContext; + } + + const parentContext = this.testContexts[parentContextId]; + + const newTestContext = { + id: testContextId, + name, + focus: this._incorporateParentValue(parentContext, 'focus', focus, CONTEXT_OPERATORS.OR), + pending: this._incorporateParentValue(parentContext, 'pending', pending, CONTEXT_OPERATORS.OR), + parentContextId, + testIds: [], + testSuiteId: this.testSuite.id, + }; + + this.testContexts[testContextId] = newTestContext; + + return newTestContext; + } + + /** + * Recursively use an operator to consolidate a test's value with that of its test + * context chain. + * @param {TestContext} parentContext - Parent context to examine for its value + * @param {String} attributeName - name of the attribute to use from parent + * @param {*} value - Value of current context or test to use as one operand with + * the parent context's value + * @param {('OR')} operator - Operator to use to consolidate current value and + * parent context's value + * @returns {*} Consolidated value, encorporating context parents' values + * @private + */ + _incorporateParentValue(parentContext, attributeName, value, operator) { + if (!parentContext) { + return value; + } + + switch (operator) { + case CONTEXT_OPERATORS.OR: + return parentContext[attributeName] || value; + default: + throw new Error(`Unknown context operator ${operator}`); + } + } + + /** + * Create a new test from the options provided and add it to the suite + * @param {Number} testId - Unique id to give to the test + * @param {Object} testAttributes - attributes to create the test with + * @param {Number} testAttributes.testContextId - Id of context test belongs to + * @param {String} testAttributes.description - Short description of the test + * @param {Function} testAttributes.func - Function that comprises the body of the test + * @param {Number} testAttributes.testSuiteId - Id of test suite test belongs to + * @param {Number} testAttributes.timeout - Number of milliseconds before test times out + * @returns {Test} New test matching provided options + * @private + */ + _createTest(testId, { testContextId, description, func, testSuiteId, timeout }) { + const newTest = { + id: testId, + testContextId, + description, + func, + testSuiteId, + status: null, + message: null, + time: 0, + timeout, + }; + + this.tests[testId] = newTest; + + return newTest; + } + +} + +/** + * Log test definition error to the console with a message indicating the test + * definition was skipped. + * @param {String} error - Error message to include in message logged to the console + */ +function testDefinitionError(error) { + console.error(`ReactNativeFirebaseTests.TestDefinitionError: ${error}`); + console.error('This test was ignored.'); +} + +export default TestSuiteDefinition; diff --git a/tests/package.json b/tests/package.json new file mode 100644 index 00000000..9c38a381 --- /dev/null +++ b/tests/package.json @@ -0,0 +1,70 @@ +{ + "name": "react-native-firebase-tests", + "version": "0.0.1", + "private": true, + "scripts": { + "start": "node node_modules/react-native/local-cli/cli.js start", + "android:dev": "react-native run-android", + "android:prod": "react-native run-android --configuration=release", + "ios:dev": "react-native run-ios", + "ios:prod": "react-native run-ios --configuration=release", + "ios:pod:install": "cd ios && rm -rf ReactNativeFirebaseDemo.xcworkspace && pod install && cd ..", + "test": "echo 'Tests should be run from within the RN application.\n\rSee https://github.com/invertase/react-native-firebase-tests/blob/master/tests/README.md for more info.'", + "build-lib-for-tests": "babel --presets=es2015-mod,es3,react-native ./lib/ -d ./__tests__/build/lib/ --source-maps", + "internal-tests": "npm run build-lib-for-tests && babel --presets=es2015-mod,es3 ./__tests__/src/ -d ./__tests__/build/ --source-maps && node ./__tests__/build/index.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/invertase/react-native-firebase.git" + }, + "bugs": { + "url": "https://github.com/invertase/react-native-firebase/issues" + }, + "homepage": "https://github.com/invertase/react-native-firebase/tests/#readme", + "dependencies": { + "babel-preset-es2015-mod": "^6.6.0", + "babel-preset-es3": "^1.0.1", + "bluebird": "^3.5.0", + "bows": "^1.6.0", + "cuid": "^1.3.8", + "deeps": "^1.4.4", + "firebase": "^3.7.0", + "js-beautify": "^1.6.11", + "lodash.groupby": "^4.6.0", + "lodash.some": "^4.6.0", + "react": "~15.4.1", + "react-native": "0.40.0", + "react-native-firebase": "file:..", + "react-native-simple-toast": "0.0.5", + "react-native-vector-icons": "^4.0.0", + "react-navigation": "^1.0.0-beta.7", + "react-redux": "^5.0.3", + "redux": "^3.6.0", + "redux-logger": "^2.8.2", + "redux-persist": "^4.4.2", + "redux-thunk": "^2.2.0", + "should": "^11.2.0", + "should-sinon": "^0.0.5", + "sinon": "https://github.com/greena13/sinon.git" + }, + "devDependencies": { + "babel-cli": "^6.24.0", + "babel-eslint": "^7.1.1", + "babel-jest": "19.0.0", + "babel-plugin-flow-react-proptypes": "^0.21.0", + "babel-preset-react-native": "1.9.1", + "colors": "^1.1.2", + "eslint": "^3.16.1", + "eslint-config-airbnb": "^14.1.0", + "eslint-plugin-flowtype": "^2.30.0", + "eslint-plugin-import": "^2.2.0", + "eslint-plugin-jsx-a11y": "^4.0.0", + "eslint-plugin-react": "^6.10.0", + "jest": "19.0.2", + "react-test-renderer": "~15.4.1", + "redux-immutable-state-invariant": "^1.2.4" + }, + "jest": { + "preset": "react-native" + } +} diff --git a/tests/src/actions/AppActions.js b/tests/src/actions/AppActions.js new file mode 100644 index 00000000..1494c85e --- /dev/null +++ b/tests/src/actions/AppActions.js @@ -0,0 +1,17 @@ +export const APP_SET_NETWORK_STATE: string = 'APP_SET_NETWORK_STATE'; +export const APP_SET_APP_STATE: string = 'APP_SET_APP_STATE'; + +export function setNetworkState(isConnected: boolean): Object { + return { + type: APP_SET_NETWORK_STATE, + isConnected, + }; +} + +export function setAppState(appState: 'active' | 'background' | 'inactive'): Object { + return { + type: APP_SET_APP_STATE, + appState, + }; +} + diff --git a/tests/src/actions/FCMActions.js b/tests/src/actions/FCMActions.js new file mode 100644 index 00000000..619f2b11 --- /dev/null +++ b/tests/src/actions/FCMActions.js @@ -0,0 +1,8 @@ +export const FCM_SET_TOKEN: string = 'FCM_SET_TOKEN'; + +export function setToken(token: string): Object { + return { + type: FCM_SET_TOKEN, + token, + }; +} diff --git a/tests/src/actions/TestActions.js b/tests/src/actions/TestActions.js new file mode 100644 index 00000000..a2ed5fe3 --- /dev/null +++ b/tests/src/actions/TestActions.js @@ -0,0 +1,26 @@ +export const TEST_SET_SUITE_STATUS: string = 'TEST_SET_SUITE_STATUS'; +export const TEST_SET_STATUS: string = 'TEST_SET_STATUS'; + +export function setSuiteStatus({ suiteId, status, time, message, progress }) { + return { + type: TEST_SET_SUITE_STATUS, + suiteId, + + status, + message, + + time, + progress, + }; +} + +export function setTestStatus({ testId, status, time = 0, message = null }) { + return { + type: TEST_SET_STATUS, + testId, + + status, + message, + time, + }; +} diff --git a/tests/src/components/Banner.js b/tests/src/components/Banner.js new file mode 100644 index 00000000..18861ece --- /dev/null +++ b/tests/src/components/Banner.js @@ -0,0 +1,51 @@ +import React from 'react'; +import { StyleSheet, View, Text } from 'react-native'; + +function Banner({ type, children, style, textStyle }) { + return ( + + + {children} + + + ); +} + +Banner.propTypes = { + type: React.PropTypes.oneOf([ + 'success', + 'warning', + 'error', + 'info', + ]), + children: React.PropTypes.oneOfType([ + React.PropTypes.string, + React.PropTypes.array, + ]).isRequired, + style: View.propTypes.style, + textStyle: Text.propTypes.style, +}; + +const styles = StyleSheet.create({ + banner: { + alignItems: 'center', + elevation: 3, + }, + bannerText: { + color: '#ffffff', + }, + warning: { + backgroundColor: '#FFC107', + }, + error: { + backgroundColor: '#f44336', + }, + success: { + backgroundColor: '#4CAF50', + }, +}); + +export default Banner; diff --git a/tests/src/components/Icon.js b/tests/src/components/Icon.js new file mode 100644 index 00000000..8a2ace43 --- /dev/null +++ b/tests/src/components/Icon.js @@ -0,0 +1,75 @@ +import React from 'react'; +import { View, TouchableHighlight } from 'react-native'; +import VectorIcon from 'react-native-vector-icons/MaterialIcons'; + +type Props = { + name: string, + size?: number, + color?: string, + allowFontScaling?: boolean, + style?: Object, + rotate?: number, + onPress?: () => void, + underlayColor?: string, +}; + +// TODO Spin? +class Icon extends React.Component { + + constructor() { + super(); + this.measured = false; + this.state = { + width: 0, + }; + } + + setDimensions(e) { + if (!this.measured) { + this.measured = true; + this.setState({ + width: e.nativeEvent.layout.width, + }); + } + } + + props: Props; + + render() { + const { name, size = 24, color = '#757575', allowFontScaling = true, style, rotate, onPress, underlayColor } = this.props; + + const icon = ( + this.setDimensions(e)} + style={[ + style, + rotate ? { transform: [{ rotate: `${rotate}deg` }] } : null, + ]} + > + + + ); + + if (!onPress) { + return icon; + } + + return ( + + {icon} + + ); + } + +} + +export default Icon; diff --git a/tests/src/components/OverviewControlButton.js b/tests/src/components/OverviewControlButton.js new file mode 100644 index 00000000..4fe778bd --- /dev/null +++ b/tests/src/components/OverviewControlButton.js @@ -0,0 +1,70 @@ +import React, { PropTypes, Component } from 'react'; +import some from 'lodash.some'; +import { connect } from 'react-redux'; + +import Toast from 'react-native-simple-toast'; + +import { runTests } from '../tests/index'; +import RunStatus from '../../lib/RunStatus'; + +import Icon from '../components/Icon'; + +class OverviewControlButton extends Component { + constructor(props, context) { + super(props, context); + + this.handleOnPress = this.handleOnPress.bind(this); + } + + testSuitesAreRunning() { + const { testSuites } = this.props; + + return some(Object.values(testSuites), ({ status }) => status === RunStatus.RUNNING); + } + + handleOnPress() { + const { focusedTestIds, pendingTestIds, tests } = this.props; + runTests(tests, { focusedTestIds, pendingTestIds }); + Toast.show('Running all suite tests.'); + } + + render() { + if (this.testSuitesAreRunning()) { + return ( + + ); + } + + return ( + + ); + } +} + +OverviewControlButton.propTypes = { + tests: PropTypes.objectOf(PropTypes.object).isRequired, + testSuites: PropTypes.objectOf(PropTypes.object).isRequired, + focusedTestIds: PropTypes.objectOf(PropTypes.bool).isRequired, + pendingTestIds: PropTypes.objectOf(PropTypes.bool).isRequired, +}; + + +function mapStateToProps({ tests, testSuites, focusedTestIds, pendingTestIds }) { + return { + tests, + testSuites, + focusedTestIds, + pendingTestIds, + }; +} + +export default connect(mapStateToProps)(OverviewControlButton); diff --git a/tests/src/components/StatusIndicator.js b/tests/src/components/StatusIndicator.js new file mode 100644 index 00000000..b6180d65 --- /dev/null +++ b/tests/src/components/StatusIndicator.js @@ -0,0 +1,52 @@ +import { View, Text } from 'react-native'; +import React, { PropTypes, Component } from 'react'; + +import RunStatus from '../../lib/RunStatus'; +import Icon from './Icon'; + +class StatusIndicator extends Component { + + render() { + const { status, progress } = this.props; + + switch (status) { + case RunStatus.RUNNING: + if (progress > 0) { + return ( + + + {progress.toFixed(0)}% + + + ); + } + + return ( + + ); + case RunStatus.OK: + return ( + + ); + case RunStatus.ERR: + return ( + + ); + default: + return null; + } + } + +} + +StatusIndicator.propTypes = { + status: PropTypes.oneOf(Object.values(RunStatus)), + progress: PropTypes.number, +}; + +StatusIndicator.defaultProps = { + status: null, + progress: 0 +}; + +module.exports = StatusIndicator; diff --git a/tests/src/components/TestControlButton.js b/tests/src/components/TestControlButton.js new file mode 100644 index 00000000..c11cf98f --- /dev/null +++ b/tests/src/components/TestControlButton.js @@ -0,0 +1,71 @@ +import React, { PropTypes, Component } from 'react'; +import { connect } from 'react-redux'; +import Toast from 'react-native-simple-toast'; + +import RunStatus from '../../lib/RunStatus'; +import { runTest } from '../tests/index'; + +import Icon from './Icon'; + +class TestControlButton extends Component { + constructor(props, context) { + super(props, context); + + this.handleOnPress = this.handleOnPress.bind(this); + } + + testIsPending() { + const { test: { id }, pendingTestIds } = this.props; + return !!pendingTestIds[id]; + } + + handleOnPress() { + const { test: { id, description } } = this.props; + + runTest(id); + Toast.show(`Running ${description}.`); + } + + render() { + const { test: { status } } = this.props; + + if (status !== RunStatus.STARTED && !this.testIsPending()) { + return ( + + ); + } + + return null; + } + +} + +TestControlButton.propTypes = { + test: PropTypes.shape({ + id: PropTypes.number.isRequired, + status: PropTypes.string, + description: PropTypes.string.isRequired, + }).isRequired, + + pendingTestIds: PropTypes.objectOf(PropTypes.bool).isRequired, +}; + +TestControlButton.defaultProps = { + +}; + +function mapStateToProps({ tests, pendingTestIds }, { testId }) { + const test = tests[testId]; + + return { + test, + pendingTestIds, + }; +} + +module.exports = connect(mapStateToProps)(TestControlButton); diff --git a/tests/src/components/TestSuiteControlButton.js b/tests/src/components/TestSuiteControlButton.js new file mode 100644 index 00000000..ca8a0cd3 --- /dev/null +++ b/tests/src/components/TestSuiteControlButton.js @@ -0,0 +1,96 @@ +import React, { PropTypes, Component } from 'react'; +import { connect } from 'react-redux'; + +import Toast from 'react-native-simple-toast'; + +import RunStatus from '../../lib/RunStatus'; +import { runTests } from '../tests/index'; + +import Icon from './Icon'; + +class TestSuiteControlButton extends Component { + constructor(props, context) { + super(props, context); + + this.toggleOnlyShowFailingTests = this.toggleOnlyShowFailingTests.bind(this); + this.startTestSuite = this.startTestSuite.bind(this); + } + + startTestSuite() { + const { testSuite: { name, testIds }, tests, focusedTestIds, pendingTestIds } = this.props; + + const testSuiteTests = testIds.reduce((memo, testId) => { + // eslint-disable-next-line no-param-reassign + memo[testId] = tests[testId]; + return memo; + }, {}); + + runTests(testSuiteTests, { focusedTestIds, pendingTestIds }); + + Toast.show(`Running ${name} tests.`); + } + + toggleOnlyShowFailingTests() { + const { onlyShowFailingTests, onFilterChange } = this.props; + onFilterChange({ onlyShowFailingTests: !onlyShowFailingTests }); + } + + render() { + const { testSuite: { status }, onlyShowFailingTests } = this.props; + + if (status === RunStatus.ERR) { + return ( + + ); + } else if (status !== RunStatus.RUNNING) { + return ( + + ); + } + + return null; + } + +} + +TestSuiteControlButton.propTypes = { + testSuite: PropTypes.shape({ + status: PropTypes.oneOf(Object.values(RunStatus)), + }).isRequired, + + tests: PropTypes.objectOf(PropTypes.object).isRequired, + focusedTestIds: PropTypes.objectOf(PropTypes.bool).isRequired, + pendingTestIds: PropTypes.objectOf(PropTypes.bool).isRequired, + + onlyShowFailingTests: PropTypes.bool, + + onFilterChange: PropTypes.func.isRequired, +}; + +TestSuiteControlButton.defaultProps = { + onlyShowFailingTests: false, +}; + + +function mapStateToProps({ tests, testSuites, focusedTestIds, pendingTestIds }, { testSuiteId }) { + const testSuite = testSuites[testSuiteId]; + + return { + tests, + testSuite, + focusedTestIds, + pendingTestIds, + }; +} + +module.exports = connect(mapStateToProps)(TestSuiteControlButton); diff --git a/tests/src/containers/CoreContainer.js b/tests/src/containers/CoreContainer.js new file mode 100644 index 00000000..82e4452a --- /dev/null +++ b/tests/src/containers/CoreContainer.js @@ -0,0 +1,83 @@ +// @flow +import React from 'react'; +import { View, Text, AppState, NetInfo, StatusBar, Platform } from 'react-native'; +import { connect } from 'react-redux'; + +import Navigator from '../navigator'; +import { setNetworkState, setAppState } from '../actions/AppActions'; + +type Props = { + dispatch: () => void, +}; + +class CoreContainer extends React.Component { + + constructor() { + super(); + this._isConnected = false; + } + + /** + * On app mount, listen for changes to app & network state + */ + componentDidMount() { + if (Platform.OS === 'android') { + StatusBar.setBackgroundColor('#0279ba'); + } + if (Platform.OS === 'ios') { + StatusBar.setBarStyle('light-content'); + } + AppState.addEventListener('change', this.handleAppStateChange); + NetInfo.isConnected.fetch().then((isConnected) => { + this.handleAppStateChange('active'); // Force connect (react debugger issue) + this.props.dispatch(setNetworkState(isConnected)); + NetInfo.isConnected.addEventListener('change', this.handleNetworkChange); + }); + } + + /** + * Remove listeners on app unmount + */ + componentWillUnmount() { + AppState.removeEventListener('change', this.handleAppStateChange); + NetInfo.isConnected.removeEventListener('change', this.handleNetworkChange); + } + + props: Props; + _isConnected: boolean; + + /** + * Handle app state changes + * https://facebook.github.io/react-native/docs/appstate.html + * @param state + */ + handleAppStateChange = (state) => { + this.props.dispatch(setAppState(state)); + if (state === 'active' && this._isConnected) { + // firestack.database().goOnline(); + } else if (state === 'background') { + // firestack.database().goOffline(); + } + }; + + /** + * Handle app network changes + * https://facebook.github.io/react-native/docs/netinfo.html + * @param isConnected + */ + handleNetworkChange = (isConnected) => { + this._isConnected = isConnected; + this.props.dispatch(setNetworkState(isConnected)); + if (isConnected) { + // firestack.database().goOnline(); + } else { + // firestack.database().goOffline(); + } + }; + + render() { + return ; + } +} + +export default connect()(CoreContainer); diff --git a/tests/src/firebase.js b/tests/src/firebase.js new file mode 100644 index 00000000..b966843f --- /dev/null +++ b/tests/src/firebase.js @@ -0,0 +1,32 @@ +import firebase from 'firebase'; +import RNfirebase from './../firebase/firebase'; + +import DatabaseContents from './tests/support/DatabaseContents'; + +const config = { + apiKey: 'AIzaSyDnVqNhxU0Biit9nCo4RorAh5ulQQwko3E', + authDomain: 'rnfirebase-b9ad4.firebaseapp.com', + databaseURL: 'https://rnfirebase-b9ad4.firebaseio.com', + storageBucket: 'rnfirebase-b9ad4.appspot.com', + messagingSenderId: '305229645282', +}; + +const instances = { + web: firebase.initializeApp(config), + native: RNfirebase.initializeApp({ + debug: __DEV__ ? '*' : false, + errorOnMissingPlayServices: false, + persistence: true, + }), +}; + +instances.web.database().ref('tests/types').set(DatabaseContents.DEFAULT); + +instances.web.database().ref('tests/priority').setWithPriority({ + foo: 'bar', +}, 666); + + +// instances.native.messaging().subscribeToTopic('fcm_test'); + +export default instances; diff --git a/tests/src/helpers.js b/tests/src/helpers.js new file mode 100644 index 00000000..2227bfea --- /dev/null +++ b/tests/src/helpers.js @@ -0,0 +1,3 @@ +// import fs from 'fs'; +import path from 'path'; + diff --git a/tests/src/main.js b/tests/src/main.js new file mode 100644 index 00000000..35086ae6 --- /dev/null +++ b/tests/src/main.js @@ -0,0 +1,64 @@ +import React, { Component } from 'react'; +import { Provider } from 'react-redux'; + +import CoreContainer from './containers/CoreContainer'; +import setupStore from './store/setup'; +import { setupSuites } from './tests/index'; + +global.Promise = require('bluebird'); + +type State = { + loading: boolean, + store: any, +}; + +function bootstrap() { + // Remove logging on production + if (!__DEV__) { + console.log = () => { + }; + console.warn = () => { + }; + console.error = () => { + }; + console.disableYellowBox = true; + } + + class Root extends Component { + constructor() { + super(); + this.state = { + loading: true, + store: null, + }; + } + + state: State; + + componentDidMount() { + setupStore((store) => { + setupSuites(store); + this.setState({ + store, + loading: false, + }); + }); + } + + render() { + if (this.state.loading) { + return null; + } + + return ( + + + + ); + } + } + + return Root; +} + +export default bootstrap(); diff --git a/tests/src/navigator.js b/tests/src/navigator.js new file mode 100644 index 00000000..d54f30d4 --- /dev/null +++ b/tests/src/navigator.js @@ -0,0 +1,20 @@ +import { StackNavigator } from 'react-navigation'; + +import Overview from './screens/Overview'; +import Suite from './screens/Suite'; +import Test from './screens/Test'; + +export default StackNavigator({ + Overview: { screen: Overview }, + Suite: { screen: Suite }, + Test: { screen: Test }, +}); + +export const initialNavState = { + index: 0, + routes: [ + { + key: 'Overview', + }, + ], +}; diff --git a/tests/src/reducers/device.js b/tests/src/reducers/device.js new file mode 100644 index 00000000..7646352d --- /dev/null +++ b/tests/src/reducers/device.js @@ -0,0 +1,35 @@ +import * as fcmTypes from '../actions/FCMActions'; +import * as appTypes from '../actions/AppActions'; + +type State = { + appState: 'string', + isConnected: boolean, + fcmToken: string, +}; + +const initialState = { + appState: 'active', + isConnected: true, + fcmToken: '', +}; + +function device(state: State = initialState, action: Object): State { + + if (action.type === appTypes.APP_SET_NETWORK_STATE) { + return { + ...state, + isConnected: action.isConnected, + }; + } + + if (action.type === appTypes.APP_SET_APP_STATE) { + return { + ...state, + appState: action.appState, + }; + } + + return state; +} + +export default device; diff --git a/tests/src/reducers/focusedTestIdsReducers.js b/tests/src/reducers/focusedTestIdsReducers.js new file mode 100644 index 00000000..c413d889 --- /dev/null +++ b/tests/src/reducers/focusedTestIdsReducers.js @@ -0,0 +1,9 @@ +import { initialState } from '../tests/index'; + +const initState = initialState(); + +function focusedTestIdsReducers(state = initState.focusedTestIds): State { + return state; +} + +export default focusedTestIdsReducers; diff --git a/tests/src/reducers/index.js b/tests/src/reducers/index.js new file mode 100644 index 00000000..17fcc7d7 --- /dev/null +++ b/tests/src/reducers/index.js @@ -0,0 +1,17 @@ +import { combineReducers } from 'redux'; + +import device from './device'; +import tests from './testsReducers'; +import testContexts from './testContextsReducers'; +import testSuites from './testSuitesReducers'; +import pendingTestIds from './pendingTestIdsReducers'; +import focusedTestIds from './focusedTestIdsReducers'; + +export default combineReducers({ + device, + pendingTestIds, + focusedTestIds, + testContexts, + tests, + testSuites, +}); diff --git a/tests/src/reducers/pendingTestIdsReducers.js b/tests/src/reducers/pendingTestIdsReducers.js new file mode 100644 index 00000000..89cebeda --- /dev/null +++ b/tests/src/reducers/pendingTestIdsReducers.js @@ -0,0 +1,9 @@ +import { initialState } from '../tests'; + +const initState = initialState(); + +function pendingTestIdsReducers(state = initState.pendingTestIds): State { + return state; +} + +export default pendingTestIdsReducers; diff --git a/tests/src/reducers/testContextsReducers.js b/tests/src/reducers/testContextsReducers.js new file mode 100644 index 00000000..201dd4d2 --- /dev/null +++ b/tests/src/reducers/testContextsReducers.js @@ -0,0 +1,9 @@ +import { initialState } from '../tests/index'; + +const initState = initialState(); + +function testsReducers(state = initState.testContexts): State { + return state; +} + +export default testsReducers; diff --git a/tests/src/reducers/testSuitesReducers.js b/tests/src/reducers/testSuitesReducers.js new file mode 100644 index 00000000..becf6514 --- /dev/null +++ b/tests/src/reducers/testSuitesReducers.js @@ -0,0 +1,23 @@ +import * as testActions from '../actions/TestActions'; +import { flatten, unflatten } from 'deeps'; +import { initialState } from '../tests/index'; + +const initState = initialState(); + +function testsReducers(state = initState.testSuites, action: Object): State { + + if (action.type === testActions.TEST_SET_SUITE_STATUS) { + const flattened = flatten(state); + + if (action.status) flattened[`${action.suiteId}.status`] = action.status; + if (action.message) flattened[`${action.suiteId}.message`] = action.message; + if (action.progress) flattened[`${action.suiteId}.progress`] = action.progress; + if (!isNaN(action.time)) flattened[`${action.suiteId}.time`] = action.time; + + return unflatten(flattened); + } + + return state; +} + +export default testsReducers; diff --git a/tests/src/reducers/testsReducers.js b/tests/src/reducers/testsReducers.js new file mode 100644 index 00000000..204e600f --- /dev/null +++ b/tests/src/reducers/testsReducers.js @@ -0,0 +1,22 @@ +import * as testActions from '../actions/TestActions'; +import { flatten, unflatten } from 'deeps'; +import { initialState } from '../tests/index'; + +const initState = initialState(); + +function testsReducers(state = initState.tests, action: Object): State { + + if (action.type === testActions.TEST_SET_STATUS) { + const flattened = flatten(state); + + flattened[`${action.testId}.status`] = action.status; + flattened[`${action.testId}.message`] = action.message; + flattened[`${action.testId}.time`] = action.time; + + return unflatten(flattened); + } + + return state; +} + +export default testsReducers; diff --git a/tests/src/screens/Overview.js b/tests/src/screens/Overview.js new file mode 100644 index 00000000..e52b2a94 --- /dev/null +++ b/tests/src/screens/Overview.js @@ -0,0 +1,299 @@ +import React, { PropTypes } from 'react'; +import { StyleSheet, View, Text, ListView, TouchableHighlight } from 'react-native'; +import { connect } from 'react-redux'; +import some from 'lodash.some'; + +import RunStatus from '../../lib/RunStatus'; + +import Banner from '../components/Banner'; +import StatusIndicator from '../components/StatusIndicator'; +import OverviewControlButton from '../components/OverviewControlButton'; + +class Overview extends React.Component { + // noinspection JSUnusedGlobalSymbols + static navigationOptions = { + title: 'Test Suites', + header: () => { + return { + style: { backgroundColor: '#0288d1' }, + tintColor: '#ffffff', + right: ( + + + + ), + }; + }, + }; + + /** + * Renders separator between ListView sections + * @param {String} sectionID + * @param {String} rowID + * @returns {XML} JSX component used as ListView separator + */ + static renderSeparator(sectionID, rowID) { + return ( + + ); + } + + /** + * Filters test suites to those that have one or more tests that should be visible. + * If one or more tests are focused it only returns test suites with focused tests, + * otherwise, it returns all test suites. + * @param {IndexedTestSuiteGroup} testSuites - group of available test suites + * @param {IdLookup} focusedTestIds - lookup for focused tests + * @returns {IndexedTestSuiteGroup} - indexed group of test suites that should be shown + */ + static testSuitesToShow({ testSuites, focusedTestIds }) { + if (Object.keys(focusedTestIds).length > 0) { + return Object.keys(testSuites).reduce((memo, testSuiteId) => { + const testSuite = testSuites[testSuiteId]; + + const testSuiteHasFocusedTests = some(testSuite.testIds, (testId) => { + return focusedTestIds[testId]; + }); + + if (testSuiteHasFocusedTests) { + // eslint-disable-next-line no-param-reassign + memo[testSuiteId] = testSuite; + } + + return memo; + }, {}); + } + + return testSuites; + } + + /** + * Copies initial values for test suites from props into state, so they may be + * rendered as a ListView + * @param {Object} props - props used to render component + * @param {Object} context - context used to render component + */ + constructor(props, context) { + super(props, context); + + this.dataSource = new ListView.DataSource({ + rowHasChanged: (r1, r2) => JSON.stringify(r1) !== JSON.stringify(r2), + }); + + this.state = { + dataBlob: this.dataSource.cloneWithRows(Overview.testSuitesToShow(props)), + }; + } + + + /** + * Copies latest test suite status into state so they may be rendered as a ListView + * @param {Object} nextProps - next props used to render component + * @param {Object.} nextProps.testSuites - test suites to render + * @param {IdLookup} nextProps.focusedTestIds - lookup for focus tests + */ + componentWillReceiveProps({ testSuites, focusedTestIds }) { + this.setState({ + dataBlob: this.dataSource.cloneWithRows(Overview.testSuitesToShow({ testSuites, focusedTestIds })), + }); + } + + /** + * Navigate to test suite screen + * @param {TestSuiteId} testSuiteId - id of test suite to navigate to + */ + goToTestSuite(testSuite) { + const { navigation: { navigate } } = this.props; + + navigate('Suite', { testSuiteId: testSuite.id, title: testSuite.name }); + } + + /** + * + * @param testSuite + * @param sectionId + * @param rowId + * @param highlight + * @returns {XML} + */ + renderRow(testSuite, sectionId, rowId, highlight) { + const { description, name, status, progress } = testSuite; + + return ( + { + this.goToTestSuite(testSuite); + highlight(); + }} + > + + + {name} + + {description} + + + + + + + + ); + } + + /** + * Renders a warning toast banner if there are one or more tests that are pending + * @returns {null|XML} Toast banner if there are test pending, else null + */ + renderPendingTestsBanner() { + const { pendingTestIds } = this.props; + + const pendingTestsCount = Object.keys(pendingTestIds).length; + + if (pendingTestsCount > 0) { + return ( + + {pendingTestsCount} pending test(s). + + ); + } + + return null; + } + + renderStatusBanner() { + const { testSuites } = this.props; + + let totalProgress = 0; + let isRunning = false; + let isErrors = false; + let totalTime = 0; + + Object.values(testSuites).forEach(({ progress, status, time }) => { + totalProgress += progress; + totalTime += time; + + if (status === RunStatus.RUNNING) { + isRunning = true; + } else if (status === RunStatus.ERR) { + isErrors = true; + } + }); + + totalProgress /= Object.keys(testSuites).length; + + if (isRunning) { + return ( + Running ({(totalTime / 1000).toFixed(0)}s) {totalProgress.toFixed(2)}% + ); + } else if (totalProgress > 0) { + if (isErrors) { + return ( + Tests Complete with errors + ); + } + + return ( + Tests Complete + ); + } + + return null; + } + + + /** + * Renders ListView of test suites that should be visible, taking into consideration + * any focused tests + * @returns {XML} ListView of test suites + */ + render() { + return ( + + { this.renderPendingTestsBanner() } + { this.renderStatusBanner() } + this.renderRow(...args)} + renderSeparator={(...args) => Overview.renderSeparator(...args)} + /> + + ); + } +} + +Overview.propTypes = { + testSuites: PropTypes.objectOf(PropTypes.shape({ + id: PropTypes.number.isRequired, + description: PropTypes.string.isRequired, + name: PropTypes.string.isRequired, + status: PropTypes.oneOf(Object.values(RunStatus)), + })).isRequired, + + tests: PropTypes.objectOf(PropTypes.shape({ + testSuiteId: PropTypes.number.isRequired, + })).isRequired, + + navigation: PropTypes.shape({ + navigate: PropTypes.func.isRequired, + }).isRequired, + + running: PropTypes.bool.isRequired, + + pendingTestIds: PropTypes.objectOf(PropTypes.bool).isRequired, + focusedTestIds: PropTypes.objectOf(PropTypes.bool).isRequired, +}; +const styles = StyleSheet.create({ + rightContainer: { + marginRight: 16, + }, + container: { + flex: 1, + backgroundColor: '#ffffff', + }, + title: { + fontSize: 17, + fontWeight: '600', + }, + description: { + fontSize: 11, + }, + statusContainer: { + flex: 1, + alignItems: 'flex-end', + }, + row: { + height: 56, + paddingHorizontal: 16, + flexDirection: 'row', + alignItems: 'center', + }, + error: { + backgroundColor: 'rgba(255, 0, 0, 0.054)', + }, + separator: { + height: 1, + backgroundColor: '#eeeeee', + }, +}); + +function mapStateToProps({ testSuites, tests, pendingTestIds, focusedTestIds }) { + return { + testSuites, + tests, + pendingTestIds, + focusedTestIds, + running: Object.values(testSuites).filter(suite => suite.status === RunStatus.RUNNING).length > 0, + }; +} + +export default connect(mapStateToProps)(Overview); diff --git a/tests/src/screens/Suite.js b/tests/src/screens/Suite.js new file mode 100644 index 00000000..884727df --- /dev/null +++ b/tests/src/screens/Suite.js @@ -0,0 +1,404 @@ +import React, { PropTypes } from 'react'; +import { StyleSheet, View, Text, ListView, TouchableHighlight } from 'react-native'; +import { connect } from 'react-redux'; + +import RunStatus from '../../lib/RunStatus'; + +import Banner from '../components/Banner'; + +import StatusIndicator from '../components/StatusIndicator'; +import TestSuiteControlButton from '../components/TestSuiteControlButton'; + +class Suite extends React.Component { + + static navigationOptions = { + title: ({ state: { params: { title } } }) => { + return title; + }, + header: ({ state: { params: { testSuiteId, onlyShowFailingTests } }, setParams }) => { + return { + style: { backgroundColor: '#0288d1' }, + tintColor: '#ffffff', + right: ( + + + + ), + }; + }, + }; + + /** + * Render test group header + * @param data + * @param title + * @returns {XML} + */ + static renderHeader(data, title) { + return ( + + + {title.toUpperCase()} + + + ); + } + + constructor(props) { + super(props); + + this.dataSource = new ListView.DataSource({ + rowHasChanged: (r1, r2) => JSON.stringify(r1) !== JSON.stringify(r2), + sectionHeaderHasChanged: (s1, s2) => s1 !== s2, + }); + + this.state = { + dataBlob: this.dataSource.cloneWithRowsAndSections(buildRowsWithSections(props)), + }; + } + + /** + * componentWillReceiveProps + * @param nextProps + */ + componentWillReceiveProps(nextProps) { + const { + tests, + testContexts, + navigation: { state: { params: { onlyShowFailingTests } } }, + } = nextProps; + + const newRowsWithSections = (() => { + if (onlyShowFailingTests) { + return Object.values(testContexts).reduce((sections, context) => { + const { name } = context; + + context.testIds.forEach((testId) => { + const test = tests[testId]; + + if (test && test.status === RunStatus.ERR) { + // eslint-disable-next-line no-param-reassign + sections[name] = sections[name] || []; + sections[name].push(test); + } + }); + + return sections; + }, {}); + } + + return buildRowsWithSections(nextProps); + })(); + + this.setState({ + dataBlob: this.dataSource.cloneWithRowsAndSections(newRowsWithSections), + }); + } + + /** + * Go to a single test + * @param testId + */ + goToTest(test) { + const { navigation: { navigate } } = this.props; + + navigate('Test', { testId: test.id, title: test.description }); + } + + /** + * Render test row + * @param test + * @param sectionId + * @param rowId + * @param highlight + * @returns {XML} + */ + renderRow(test, sectionId, rowId, highlight) { + const { pendingTestIds } = this.props; + const { status, description, id } = test; + + return ( + { + this.goToTest(test); + highlight(); + }} + > + + + + {description} + + + + + + + + ); + } + + /** + * + * @param sectionID + * @param rowID + * @returns {XML} + */ + renderSeparator(sectionID, rowID) { + return ( + + ); + } + + renderPendingTestsBanner() { + const { testSuite: { testIds }, pendingTestIds } = this.props; + + let pendingTestsCount = 0; + + testIds.forEach((testId) => { + if (pendingTestIds[testId]) { + pendingTestsCount += 1; + } + }); + + if (pendingTestsCount) { + return ( + + {pendingTestsCount} pending test(s). + + ); + } + + return null; + } + + renderStatusBanner() { + const { testSuite: { status, progress, time, message } } = this.props; + + switch (status) { + case RunStatus.RUNNING: + + return ( + + Tests are currently running ({ progress.toFixed(2) }%). + + ); + + case RunStatus.OK: + + return ( + + Tests passed. ({ time }ms) + + ); + + case RunStatus.ERR: + + return ( + + {message} ({time}ms) + + ); + + default: + return null; + } + } + + /** + * + * @returns {XML} + */ + render() { + const { dataBlob } = this.state; + + return ( + + + { this.renderPendingTestsBanner() } + { this.renderStatusBanner() } + + Suite.renderHeader(...args)} + renderRow={(...args) => this.renderRow(...args)} + renderSeparator={(...args) => this.renderSeparator(...args)} + /> + + ); + } + +} + +Suite.propTypes = { + navigation: PropTypes.shape({ + setParams: PropTypes.func.isRequired, + navigate: PropTypes.func.isRequired, + state: PropTypes.shape({ + params: PropTypes.object, + onlyShowFailingTests: PropTypes.bool, + }).isRequired, + }).isRequired, + + testSuite: PropTypes.shape({ + status: PropTypes.string, + progress: PropTypes.number, + time: PropTypes.number, + message: PropTypes.string, + }).isRequired, + + testContexts: PropTypes.objectOf(PropTypes.shape({ + name: PropTypes.string.isRequired, + testIds: PropTypes.arrayOf(PropTypes.number).isRequired, + })).isRequired, + + tests: PropTypes.objectOf(PropTypes.shape({ + id: PropTypes.number, + description: PropTypes.string, + status: PropTypes.oneOf(Object.values(RunStatus)), + })).isRequired, + + pendingTestIds: PropTypes.objectOf(PropTypes.bool).isRequired, + focusedTestIds: PropTypes.objectOf(PropTypes.bool).isRequired, +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: '#ffffff', + }, + banner: { + alignItems: 'center', + elevation: 3, + }, + bannerText: { + color: '#ffffff', + }, + inProgress: { + backgroundColor: '#FFC107', + }, + errorBanner: { + backgroundColor: '#f44336', + }, + header: { + elevation: 3, + justifyContent: 'center', + height: 25, + paddingHorizontal: 16, + backgroundColor: '#ECEFF1', + }, + headerText: { + fontWeight: '800', + }, + row: { + paddingHorizontal: 16, + height: 48, + flexDirection: 'row', + }, + rowContent: { + justifyContent: 'center', + }, + disabledRow: { + color: '#c3c3c3', + }, + error: { + backgroundColor: 'rgba(255, 0, 0, 0.054)', + }, + separator: { + height: 1, + backgroundColor: '#eeeeee', + }, +}); + +function buildRowsWithSections({ testContexts, tests, focusedTestIds }) { + const someTestsAreFocused = Object.keys(focusedTestIds).length > 0; + + return Object.values(testContexts).reduce((sections, testContext) => { + const { testIds } = testContext; + + const contextTestsToShow = testIds.reduce((memo, testId) => { + const test = tests[testId]; + + if (someTestsAreFocused) { + if (focusedTestIds[testId]) { + memo.push(test); + } + } else { + memo.push(test); + } + + return memo; + }, []); + + if (contextTestsToShow.length > 0) { + const effectiveContext = highestNonRootAncestor(testContext, testContexts); + // eslint-disable-next-line no-param-reassign + sections[effectiveContext.name] = sections[effectiveContext.name] || []; + // eslint-disable-next-line no-param-reassign + sections[effectiveContext.name] = sections[effectiveContext.name].concat(contextTestsToShow); + } + + return sections; + }, {}); +} + +function highestNonRootAncestor(testContext, testContexts) { + const parentContextId = testContext.parentContextId; + + if (parentContextId) { + const parentContext = testContexts[parentContextId]; + const parentContextIsNotRoot = parentContext && parentContext.parentContextId; + + if (parentContextIsNotRoot) { + return highestNonRootAncestor(parentContext, testContexts); + } + } + + return testContext; +} + +function mapStateToProps(state, { navigation: { state: { params: { testSuiteId } } } }) { + const { tests, testContexts, testSuites, pendingTestIds, focusedTestIds } = state; + const testSuite = testSuites[testSuiteId]; + + const testSuiteContexts = testSuite.testContextIds.reduce((suiteContexts, contextId) => { + // eslint-disable-next-line no-param-reassign + suiteContexts[contextId] = testContexts[contextId]; + + return suiteContexts; + }, {}); + + const testSuiteTests = testSuite.testIds.reduce((suiteTests, testId) => { + // eslint-disable-next-line no-param-reassign + suiteTests[testId] = tests[testId]; + + return suiteTests; + }, {}); + + return { + testSuite, + testContexts: testSuiteContexts, + tests: testSuiteTests, + pendingTestIds, + focusedTestIds, + }; +} + +export default connect(mapStateToProps)(Suite); diff --git a/tests/src/screens/Test.js b/tests/src/screens/Test.js new file mode 100644 index 00000000..a8e0e233 --- /dev/null +++ b/tests/src/screens/Test.js @@ -0,0 +1,149 @@ +import React, { PropTypes } from 'react'; +import { StyleSheet, View, Text, ScrollView } from 'react-native'; +import { connect } from 'react-redux'; +import { js_beautify as beautify } from 'js-beautify'; + +import Banner from '../components/Banner'; +import RunStatus from '../../lib/RunStatus'; +import TestControlButton from '../components/TestControlButton'; + +class Test extends React.Component { + + static navigationOptions = { + title: ({ state: { params: { title } } }) => { + return title; + }, + header: ({ state: { params: { testId } } }) => { + return { + style: { backgroundColor: '#0288d1' }, + tintColor: '#ffffff', + right: ( + + + + ), + }; + }, + }; + + static renderBanner({ status, time }) { + switch (status) { + case RunStatus.RUNNING: + return ( + + Test is currently running. + + ); + case RunStatus.OK: + return ( + + Test passed. ({time}ms) + + ); + case RunStatus.ERR: + return ( + + Test failed. ({time}ms) + + ); + default: + return null; + } + } + + componentDidMount() { + const { navigation: { setParams }, test } = this.props; + + setParams({ test }); + } + + renderError() { + const { test: { message } } = this.props; + + if (message) { + return ( + + Test Error + + {message} + + + ); + } + + return null; + } + + + render() { + const { test: { func, status, time } } = this.props; + + return ( + + {Test.renderBanner({ status, time })} + + {this.renderError()} + Test Code Preview + + + {beautify(removeLastLine(removeFirstLine(func.toString())), { indent_size: 4, break_chained_methods: true })} + + + + + ); + } +} + +Test.propTypes = { + test: PropTypes.shape({ + status: PropTypes.string, + time: PropTypes.number, + message: PropTypes.string, + func: PropTypes.function, + }).isRequired, + + navigation: PropTypes.shape({ + setParams: PropTypes.func.isRequired, + }).isRequired, +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: '#ffffff', + }, + content: {}, + code: { + backgroundColor: '#3F373A', + color: '#c3c3c3', + padding: 5, + fontSize: 12, + }, + codeHeader: { + fontWeight: '600', + fontSize: 18, + backgroundColor: '#000', + color: '#fff', + padding: 5, + }, +}); + +function select({ tests }, { navigation: { state: { params: { testId } } } }) { + const test = tests[testId]; + + return { + test, + }; +} + +function removeLastLine(multiLineString) { + const index = multiLineString.lastIndexOf('\n'); + return multiLineString.substring(0, index); +} + +function removeFirstLine(multiLineString) { + return multiLineString.substring(multiLineString.indexOf('\n') + 1); +} + +export default connect(select)(Test); diff --git a/tests/src/store/setup.js b/tests/src/store/setup.js new file mode 100644 index 00000000..06cc0107 --- /dev/null +++ b/tests/src/store/setup.js @@ -0,0 +1,43 @@ +import { AsyncStorage } from 'react-native'; +import { applyMiddleware, createStore, compose } from 'redux'; +import thunk from 'redux-thunk'; +import reduxLogger from 'redux-logger'; +import { persistStore, autoRehydrate } from 'redux-persist'; + +import whitelist from './whitelist'; +import reducers from '../reducers'; + +function setup(done) { + const isDev = global.isDebuggingInChrome || __DEV__; + + const logger = reduxLogger({ + predicate: () => isDev, + collapsed: true, + duration: true, + }); + + // AsyncStorage.clear(); + + // Setup redux middleware + const middlewares = [autoRehydrate()]; + + middlewares.push(applyMiddleware(...[thunk])); + + if (isDev) { + middlewares.push(applyMiddleware(...[logger])); + middlewares.push(applyMiddleware(require('redux-immutable-state-invariant')())); + } + + const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; + + const store = createStore(reducers, {}, composeEnhancers(...middlewares)); + + // Attach the store to the Chrome debug window + if (global.isDebuggingInChrome) { + window.store = store; + } + + persistStore(store, { whitelist, storage: AsyncStorage }, () => done(store)); +} + +export default setup; diff --git a/tests/src/store/whitelist.js b/tests/src/store/whitelist.js new file mode 100644 index 00000000..1c4f017e --- /dev/null +++ b/tests/src/store/whitelist.js @@ -0,0 +1 @@ +export default ['']; diff --git a/tests/src/tests/analytics/analytics.js b/tests/src/tests/analytics/analytics.js new file mode 100644 index 00000000..105c585c --- /dev/null +++ b/tests/src/tests/analytics/analytics.js @@ -0,0 +1,64 @@ + +export default function addTests({ describe, it, firebase }) { + describe('Analytics', () => { + it('logEvent: it should log a text event without error', () => { + return new Promise((resolve) => { + firebase.native.analytics().logEvent('test_event'); + resolve(); + }); + }); + + it('logEvent: it should log a text event with parameters without error', () => { + return new Promise((resolve) => { + firebase.native.analytics().logEvent('test_event', { + boolean: true, + number: 1, + string: 'string', + }); + resolve(); + }); + }); + + it('setAnalyticsCollectionEnabled: it should run without error', () => { + return new Promise((resolve) => { + firebase.native.analytics().setAnalyticsCollectionEnabled(true); + resolve(); + }); + }); + + it('setCurrentScreen: it should run without error', () => { + return new Promise((resolve) => { + firebase.native.analytics().setCurrentScreen('test screen', 'test class override'); + resolve(); + }); + }); + + it('setMinimumSessionDuration: it should run without error', () => { + return new Promise((resolve) => { + firebase.native.analytics().setMinimumSessionDuration(10000); + resolve(); + }); + }); + + it('setSessionTimeoutDuration: it should run without error', () => { + return new Promise((resolve) => { + firebase.native.analytics().setSessionTimeoutDuration(1800000); + resolve(); + }); + }); + + it('setUserId: it should run without error', () => { + return new Promise((resolve) => { + firebase.native.analytics().setUserId('test-id'); + resolve(); + }); + }); + + it('setUserProperty: it should run without error', () => { + return new Promise((resolve) => { + firebase.native.analytics().setUserProperty('test-property', 'test-value'); + resolve(); + }); + }); + }); +} diff --git a/tests/src/tests/analytics/index.js b/tests/src/tests/analytics/index.js new file mode 100644 index 00000000..84a18d71 --- /dev/null +++ b/tests/src/tests/analytics/index.js @@ -0,0 +1,9 @@ +import firebase from '../../firebase'; +import TestSuite from '../../../lib/TestSuite'; +import analyticsTests from './analytics'; + +const suite = new TestSuite('Analytics', 'firebase.analytics()', firebase); + +suite.addTests(analyticsTests); + +export default suite; diff --git a/tests/src/tests/auth/authTests.js b/tests/src/tests/auth/authTests.js new file mode 100644 index 00000000..c9870069 --- /dev/null +++ b/tests/src/tests/auth/authTests.js @@ -0,0 +1,311 @@ +import should from 'should'; + +function randomString(length, chars) { + let mask = ''; + if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz'; + if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + if (chars.indexOf('#') > -1) mask += '0123456789'; + if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\'; + let result = ''; + for (let i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))]; + return result; +} + +function authTests({ tryCatch, describe, it, firebase }) { + describe('Anonymous', () => { + it('it should sign in anonymously', () => { + const successCb = (currentUser) => { + currentUser.should.be.an.Object(); + currentUser.uid.should.be.a.String(); + currentUser.toJSON().should.be.an.Object(); + should.equal(currentUser.toJSON().email, null); + currentUser.isAnonymous.should.equal(true); + currentUser.providerId.should.equal('firebase'); + + firebase.native.auth().currentUser.uid.should.be.a.String(); + + return firebase.native.auth().signOut(); + }; + + return firebase.native.auth().signInAnonymously().then(successCb); + }); + }); + + describe('Link', () => { + it('it should link anonymous account <-> email account', () => { + const random = randomString(12, '#aA'); + const email = `${random}@${random}.com`; + const pass = random; + + const successCb = (currentUser) => { + currentUser.should.be.an.Object(); + currentUser.uid.should.be.a.String(); + currentUser.toJSON().should.be.an.Object(); + should.equal(currentUser.toJSON().email, null); + currentUser.isAnonymous.should.equal(true); + currentUser.providerId.should.equal('firebase'); + firebase.native.auth().currentUser.uid.should.be.a.String(); + + const credential = firebase.native.auth.EmailAuthProvider.credential(email, pass); + + return currentUser + .link(credential) + .then((linkedUser) => { + linkedUser.should.be.an.Object(); + linkedUser.uid.should.be.a.String(); + linkedUser.toJSON().should.be.an.Object(); + linkedUser.toJSON().email.should.eql(email); + linkedUser.isAnonymous.should.equal(false); + linkedUser.providerId.should.equal('firebase'); + return firebase.native.auth().signOut(); + }).catch((error) => { + return firebase.native.auth().signOut().then(() => { + return Promise.reject(error); + }); + }); + }; + + return firebase.native.auth().signInAnonymously().then(successCb); + }); + + it('it should error on link anon <-> email if email already exists', () => { + const email = 'test@test.com'; + const pass = 'test1234'; + + const successCb = (currentUser) => { + currentUser.should.be.an.Object(); + currentUser.uid.should.be.a.String(); + currentUser.toJSON().should.be.an.Object(); + should.equal(currentUser.toJSON().email, null); + currentUser.isAnonymous.should.equal(true); + currentUser.providerId.should.equal('firebase'); + firebase.native.auth().currentUser.uid.should.be.a.String(); + + const credential = firebase.native.auth.EmailAuthProvider.credential(email, pass); + + return currentUser + .link(credential) + .then(() => { + return firebase.native.auth().signOut().then(() => { + return Promise.reject(new Error('Did not error on link')); + }); + }).catch((error) => { + return firebase.native.auth().signOut().then(() => { + error.code.should.equal('auth/email-already-in-use'); + error.message.should.equal('The email address is already in use by another account.'); + return Promise.resolve(); + }); + }); + }; + + return firebase.native.auth().signInAnonymously().then(successCb); + }); + }); + + describe('Email - Login', () => { + it('it should login with email and password', () => { + const email = 'test@test.com'; + const pass = 'test1234'; + + const successCb = (currentUser) => { + currentUser.should.be.an.Object(); + currentUser.uid.should.be.a.String(); + currentUser.toJSON().should.be.an.Object(); + currentUser.toJSON().email.should.eql('test@test.com'); + currentUser.isAnonymous.should.equal(false); + currentUser.providerId.should.equal('firebase'); + + firebase.native.auth().currentUser.uid.should.be.a.String(); + + return firebase.native.auth().signOut(); + }; + + return firebase.native.auth().signInWithEmailAndPassword(email, pass).then(successCb); + }); + + it('it should error on login if user is disabled', () => { + const email = 'disabled@account.com'; + const pass = 'test1234'; + + const successCb = () => { + return Promise.reject(new Error('Did not error.')); + }; + + const failureCb = (error) => { + error.code.should.equal('auth/user-disabled'); + error.message.should.equal('The user account has been disabled by an administrator.'); + return Promise.resolve(); + }; + + return firebase.native.auth().signInWithEmailAndPassword(email, pass).then(successCb).catch(failureCb); + }); + + it('it should error on login if password incorrect', () => { + const email = 'test@test.com'; + const pass = 'test1234666'; + + const successCb = () => { + return Promise.reject(new Error('Did not error.')); + }; + + const failureCb = (error) => { + error.code.should.equal('auth/wrong-password'); + error.message.should.equal('The password is invalid or the user does not have a password.'); + return Promise.resolve(); + }; + + return firebase.native.auth().signInWithEmailAndPassword(email, pass).then(successCb).catch(failureCb); + }); + + it('it should error on login if user not found', () => { + const email = 'randomSomeone@fourOhFour.com'; + const pass = 'test1234'; + + const successCb = () => { + return Promise.reject(new Error('Did not error.')); + }; + + const failureCb = (error) => { + error.code.should.equal('auth/user-not-found'); + error.message.should.equal('There is no user record corresponding to this identifier. The user may have been deleted.'); + return Promise.resolve(); + }; + + return firebase.native.auth().signInWithEmailAndPassword(email, pass).then(successCb).catch(failureCb); + }); + }); + + describe('Email - Create', () => { + it('it should create a user with an email and password', () => { + const random = randomString(12, '#aA'); + const email = `${random}@${random}.com`; + const pass = random; + + const successCb = (newUser) => { + newUser.uid.should.be.a.String(); + newUser.email.should.equal(email.toLowerCase()); + newUser.emailVerified.should.equal(false); + newUser.isAnonymous.should.equal(false); + newUser.providerId.should.equal('firebase'); + }; + + return firebase.native.auth().createUserWithEmailAndPassword(email, pass).then(successCb); + }); + + it('it should error on create with invalid email', () => { + const random = randomString(12, '#aA'); + const email = `${random}${random}.com.boop.shoop`; + const pass = random; + + const successCb = () => { + return Promise.reject(new Error('Did not error.')); + }; + + const failureCb = (error) => { + error.code.should.equal('auth/invalid-email'); + error.message.should.equal('The email address is badly formatted.'); + return Promise.resolve(); + }; + + return firebase.native.auth().createUserWithEmailAndPassword(email, pass).then(successCb).catch(failureCb); + }); + + it('it should error on create if email in use', () => { + const email = 'test@test.com'; + const pass = 'test123456789'; + + const successCb = () => { + return Promise.reject(new Error('Did not error.')); + }; + + const failureCb = (error) => { + error.code.should.equal('auth/email-already-in-use'); + error.message.should.equal('The email address is already in use by another account.'); + return Promise.resolve(); + }; + + return firebase.native.auth().createUserWithEmailAndPassword(email, pass).then(successCb).catch(failureCb); + }); + + it('it should error on create if password weak', () => { + const email = 'testy@testy.com'; + const pass = '123'; + + const successCb = () => { + return Promise.reject(new Error('Did not error.')); + }; + + const failureCb = (error) => { + error.code.should.equal('auth/weak-password'); + // cannot test this message - it's different on the web client than ios/android return + // error.message.should.equal('The given password is invalid.'); + return Promise.resolve(); + }; + + return firebase.native.auth().createUserWithEmailAndPassword(email, pass).then(successCb).catch(failureCb); + }); + }); + + describe('Misc', () => { + it('it should delete a user', () => { + const random = randomString(12, '#aA'); + const email = `${random}@${random}.com`; + const pass = random; + + const successCb = (newUser) => { + newUser.uid.should.be.a.String(); + newUser.email.should.equal(email.toLowerCase()); + newUser.emailVerified.should.equal(false); + newUser.isAnonymous.should.equal(false); + newUser.providerId.should.equal('firebase'); + return firebase.native.auth().currentUser.delete(); + }; + + return firebase.native.auth().createUserWithEmailAndPassword(email, pass).then(successCb); + }); + + it('it should return a token via getToken', () => { + const random = randomString(12, '#aA'); + const email = `${random}@${random}.com`; + const pass = random; + + const successCb = (newUser) => { + newUser.uid.should.be.a.String(); + newUser.email.should.equal(email.toLowerCase()); + newUser.emailVerified.should.equal(false); + newUser.isAnonymous.should.equal(false); + newUser.providerId.should.equal('firebase'); + + return newUser.getToken().then((token) => { + token.should.be.a.String(); + token.length.should.be.greaterThan(24); + return firebase.native.auth().currentUser.delete(); + }); + }; + + return firebase.native.auth().createUserWithEmailAndPassword(email, pass).then(successCb); + }); + + it('it should reject signOut if no currentUser', () => { + return new Promise((resolve, reject) => { + if (firebase.native.auth().currentUser) { + return reject(new Error(`A user is currently signed in. ${firebase.native.auth().currentUser.uid}`)); + } + + const successCb = tryCatch(() => { + reject(new Error('No signOut error returned')); + }, reject); + + const failureCb = tryCatch((error) => { + error.code.should.equal('auth/no_current_user'); + error.message.should.equal('No user currently signed in.'); + resolve(); + }, reject); + + return firebase.native.auth().signOut().then(successCb).catch(failureCb); + }); + }); + }); +} + +export default authTests; diff --git a/tests/src/tests/auth/index.js b/tests/src/tests/auth/index.js new file mode 100644 index 00000000..fff18020 --- /dev/null +++ b/tests/src/tests/auth/index.js @@ -0,0 +1,10 @@ +import firebase from '../../firebase'; +import TestSuite from '../../../lib/TestSuite'; + +import authTests from './authTests'; + +const suite = new TestSuite('Auth', 'firebase.auth()', firebase); + +suite.addTests(authTests); + +export default suite; diff --git a/tests/src/tests/crash/index.js b/tests/src/tests/crash/index.js new file mode 100644 index 00000000..9755c28d --- /dev/null +++ b/tests/src/tests/crash/index.js @@ -0,0 +1,10 @@ +import firebase from '../../firebase'; +import TestSuite from '../../../lib/TestSuite'; +import logTests from './log'; + +const suite = new TestSuite('Crash', 'firebase.crash()', firebase); + +// bootstrap tests +suite.addTests(logTests); + +export default suite; diff --git a/tests/src/tests/crash/log.js b/tests/src/tests/crash/log.js new file mode 100644 index 00000000..c23787a7 --- /dev/null +++ b/tests/src/tests/crash/log.js @@ -0,0 +1,17 @@ +export default function addTests({ describe, it, firebase }) { + describe('Log', () => { + it('log: it should log without error', () => { + return new Promise((resolve) => { + firebase.native.crash().log('Test log'); + resolve(); + }); + }); + + it('logcat: it should log without error', () => { + return new Promise((resolve) => { + firebase.native.crash().logcat(0, 'LogTest', 'Test log'); + resolve(); + }); + }); + }); +} diff --git a/tests/src/tests/database/index.js b/tests/src/tests/database/index.js new file mode 100644 index 00000000..39cd7e85 --- /dev/null +++ b/tests/src/tests/database/index.js @@ -0,0 +1,21 @@ +import firebase from '../../firebase'; +import TestSuite from '../../../lib/TestSuite'; + +/* + Test suite files + */ + +import snapshotTests from './snapshot'; +import refTestGroups from './ref/index'; + +const suite = new TestSuite('Database', 'firebase.database()', firebase); + +/* + Register tests with test suite + */ + +suite.addTests(refTestGroups); +suite.addTests(snapshotTests); + +export default suite; + diff --git a/tests/src/tests/database/ref/childTests.js b/tests/src/tests/database/ref/childTests.js new file mode 100644 index 00000000..9a97c434 --- /dev/null +++ b/tests/src/tests/database/ref/childTests.js @@ -0,0 +1,69 @@ +function childTests({ describe, it, context, firebase }) { + describe('ref().child', () => { + context('when passed a shallow path', () => { + it('returns correct child ref', () => { + // Setup + + const ref = firebase.native.database().ref('tests'); + + // Test + + const childRef = ref.child('tests'); + + // Assertion + + childRef.key.should.eql('tests'); + }); + }); + + context('when passed a nested path', () => { + it('returns correct child ref', () => { + // Setup + + const ref = firebase.native.database().ref('tests'); + + // Test + + const grandChildRef = ref.child('tests/number'); + + // Assertion + + grandChildRef.key.should.eql('number'); + }); + }); + + context('when passed a path that doesn\'t exist', () => { + it('creates a reference, anyway', () => { + // Setup + + const ref = firebase.native.database().ref('tests'); + + // Test + + const grandChildRef = ref.child('doesnt/exist'); + + // Assertion + + grandChildRef.key.should.eql('exist'); + }); + }); + + context('when passed an invalid path', () => { + it('creates a reference, anyway', () => { + // Setup + + const ref = firebase.native.database().ref('tests'); + + // Test + + const grandChildRef = ref.child('does$&nt/exist'); + + // Assertion + + grandChildRef.key.should.eql('exist'); + }); + }); + }); +} + +export default childTests; diff --git a/tests/src/tests/database/ref/factoryTests.js b/tests/src/tests/database/ref/factoryTests.js new file mode 100644 index 00000000..3a4e0c1b --- /dev/null +++ b/tests/src/tests/database/ref/factoryTests.js @@ -0,0 +1,38 @@ +import DatabaseContents from '../../support/DatabaseContents'; + +function factoryTests({ describe, it, firebase }) { + describe('ref()', () => { + it('returns root reference when provided no path', () => { + // Setup + + const ref = firebase.native.database().ref(); + + // Test + + + // Assertion + + (ref.key === null).should.be.true(); + (ref.parent === null).should.be.true(); + }); + + it('returns reference to data at path', async () => { + // Setup + + const ref = firebase.native.database().ref('tests/types/number'); + + // Test + let valueAtRef; + + await ref.once('value', (snapshot) => { + valueAtRef = snapshot.val(); + }); + + // Assertion + + valueAtRef.should.eql(DatabaseContents.DEFAULT.number); + }); + }); +} + +export default factoryTests; diff --git a/tests/src/tests/database/ref/index.js b/tests/src/tests/database/ref/index.js new file mode 100644 index 00000000..15b7424d --- /dev/null +++ b/tests/src/tests/database/ref/index.js @@ -0,0 +1,43 @@ +import onTests from './onTests'; +import offTests from './offTests'; +import onceTests from './onceTests'; +import setTests from './setTests'; +import updateTests from './updateTests'; +import removeTests from './removeTests'; +import pushTests from './pushTests'; +import factoryTests from './factoryTests'; +import keyTests from './keyTests'; +import parentTests from './parentTests'; +import childTests from './childTests'; +import isEqualTests from './isEqualTests'; +import refTests from './refTests'; +import rootTests from './rootTests'; +import transactionTests from './transactionTests'; +import queryTests from './queryTests'; + +import DatabaseContents from '../../support/DatabaseContents'; + +const testGroups = [ + factoryTests, keyTests, parentTests, childTests, rootTests, + pushTests, onTests, offTests, onceTests, updateTests, removeTests, setTests, + transactionTests, queryTests, refTests, isEqualTests, +]; + +function registerTestSuite(testSuite) { + testSuite.beforeEach(async function () { + this._databaseRef = testSuite.firebase.native.database().ref('tests/types'); + + await this._databaseRef.set(DatabaseContents.DEFAULT); + }); + + testSuite.afterEach(async function () { + await this._databaseRef.set(DatabaseContents.DEFAULT); + }); + + testGroups.forEach((testGroup) => { + testGroup(testSuite); + }); +} + + +module.exports = registerTestSuite; diff --git a/tests/src/tests/database/ref/isEqualTests.js b/tests/src/tests/database/ref/isEqualTests.js new file mode 100644 index 00000000..3fee2a6a --- /dev/null +++ b/tests/src/tests/database/ref/isEqualTests.js @@ -0,0 +1,41 @@ +function isEqualTests({ describe, before, it, firebase }) { + describe('ref().isEqual()', () => { + before(() => { + this.ref = firebase.native.database().ref('tests/types'); + }); + + it('returns true when the reference is for the same location', () => { + // Setup + + const ref2 = firebase.native.database().ref('tests/types'); + + // Assertion + + this.ref.isEqual(ref2).should.eql(true); + }); + + it('returns false when the reference is for a different location', () => { + // Setup + + const ref2 = firebase.native.database().ref('tests/types/number'); + + // Assertion + + this.ref.isEqual(ref2).should.eql(false); + }); + + it('returns false when the reference is null', () => { + // Assertion + + this.ref.isEqual(null).should.eql(false); + }); + + it('returns false when the reference is not a Reference', () => { + // Assertion + + this.ref.isEqual(1).should.eql(false); + }); + }); +} + +export default isEqualTests; diff --git a/tests/src/tests/database/ref/keyTests.js b/tests/src/tests/database/ref/keyTests.js new file mode 100644 index 00000000..30b2aac0 --- /dev/null +++ b/tests/src/tests/database/ref/keyTests.js @@ -0,0 +1,30 @@ +function keyTests({ describe, it, firebase }) { + describe('ref().key', () => { + it('returns null for root ref', () => { + // Setup + + const ref = firebase.native.database().ref(); + + // Test + + + // Assertion + + (ref.key === null).should.be.true(); + }); + + it('returns correct key for path', () => { + // Setup + + const ref = firebase.native.database().ref('tests/types/number'); + const arrayItemRef = firebase.native.database().ref('tests/types/array/1'); + + // Assertion + + ref.key.should.eql('number'); + arrayItemRef.key.should.eql('1'); + }); + }); +} + +export default keyTests; diff --git a/tests/src/tests/database/ref/offTests.js b/tests/src/tests/database/ref/offTests.js new file mode 100644 index 00000000..f92d1d2a --- /dev/null +++ b/tests/src/tests/database/ref/offTests.js @@ -0,0 +1,303 @@ +import { Platform } from 'react-native'; +import should from 'should'; +import sinon from 'sinon'; + +import DatabaseContents from '../../support/DatabaseContents'; + +function offTests({ describe, it, xcontext, context, firebase }) { + describe('ref().off()', () => { + it('doesn\'t unbind children callbacks', async () => { + // Setup + + const parentCallback = sinon.spy(); + const childCallback = sinon.spy(); + + const parentRef = firebase.native.database().ref('tests/types'); + const childRef = firebase.native.database().ref('tests/types/string'); + + await new Promise((resolve) => { + parentRef.on('value', () => { + parentCallback(); + resolve(); + }); + }); + + await new Promise((resolve) => { + childRef.on('value', () => { + childCallback(); + resolve(); + }); + }); + + parentCallback.should.be.calledOnce(); + childCallback.should.be.calledOnce(); + + // Returns nothing + const resp = await parentRef.off(); + should(resp, undefined); + + // Trigger event parent callback is listening to + await parentRef.set(DatabaseContents.DEFAULT); + + // parent and child callbacks should not have been called any more + parentCallback.should.be.calledOnce(); + childCallback.should.be.calledOnce(); + + // Trigger event child callback is listening to + await childRef.set(DatabaseContents.DEFAULT.string); + + // child callback should still be listening + childCallback.should.be.calledOnce(); + + // Teardown + await childRef.off(); + }); + + context('when passed no arguments', () => { + context('and there are no callbacks bound', () => { + it('does nothing', () => { + const ref = firebase.native.database().ref('tests/types/array'); + + should(ref.off(), undefined); + }); + }); + + it('stops all callbacks listening for all changes', async () => { + // Setup + + const valueCallback = sinon.spy(); + const childAddedCallback = sinon.spy(); + + const ref = firebase.native.database().ref('tests/types/array'); + const arrayLength = DatabaseContents.DEFAULT.array.length; + + await new Promise((resolve) => { + ref.on('child_added', () => { + childAddedCallback(); + resolve(); + }); + }); + + await new Promise((resolve) => { + ref.on('value', () => { + valueCallback(); + resolve(); + }); + }); + + valueCallback.should.be.calledOnce(); + childAddedCallback.should.have.callCount(arrayLength); + + // Check childAddedCallback is really attached + await ref.push(DatabaseContents.DEFAULT.number); + // TODO: Android: There is definitely a single listener, but value is called three times + // rather than the two you'd perhaps expect + const expectedCount = Platform.OS === 'ios' ? 2 : 3; + valueCallback.should.be.callCount(expectedCount); + childAddedCallback.should.be.callCount(arrayLength + 1); + + // Returns nothing + const resp = await ref.off(); + should(resp, undefined); + + // Trigger both callbacks + + await ref.set(DatabaseContents.DEFAULT.array); + await ref.push(DatabaseContents.DEFAULT.number); + + // Callbacks should have been unbound and not called again + valueCallback.should.be.callCount(expectedCount); + childAddedCallback.should.be.callCount(arrayLength + 1); + }); + }); + + context('when passed an event type', () => { + context('and there are no callbacks bound', () => { + it('does nothing', () => { + const ref = firebase.native.database().ref('tests/types/array'); + + should(ref.off('value'), undefined); + }); + }); + + context('that is invalid', () => { + it('does nothing', () => { + const ref = firebase.native.database().ref('tests/types/array'); + + should(ref.off('invalid'), undefined); + }); + }); + + it('detaches all callbacks listening for that event', async () => { + // Setup + + const callbackA = sinon.spy(); + const callbackB = sinon.spy(); + + const ref = firebase.native.database().ref('tests/types/string'); + + await new Promise((resolve) => { + ref.on('value', () => { + callbackA(); + resolve(); + }); + }); + + await new Promise((resolve) => { + ref.on('value', () => { + callbackB(); + resolve(); + }); + }); + + callbackA.should.be.calledOnce(); + callbackB.should.be.calledOnce(); + + // Returns nothing + const resp = await ref.off('value'); + should(resp, undefined); + + // Assertions + + await ref.set(DatabaseContents.DEFAULT.string); + + // Callbacks should have been unbound and not called again + callbackA.should.be.calledOnce(); + callbackB.should.be.calledOnce(); + }); + }); + + context('when passed a particular callback', () => { + context('and there are no callbacks bound', () => { + it('does nothing', () => { + const ref = firebase.native.database().ref('tests/types/array'); + + should(ref.off('value', sinon.spy()), undefined); + }); + }); + + it('detaches only that callback', async () => { + // Setup + let callbackA; + let callbackB; + const spyA = sinon.spy(); + const spyB = sinon.spy(); + + const ref = firebase.native.database().ref('tests/types/string'); + + // Attach the callback the first time + await new Promise((resolve) => { + callbackA = () => { + spyA(); + resolve(); + }; + ref.on('value', callbackA); + }); + + // Attach the callback the second time + await new Promise((resolve) => { + callbackB = () => { + spyB(); + resolve(); + }; + ref.on('value', callbackB); + }); + + spyA.should.be.calledOnce(); + spyB.should.be.calledOnce(); + + // Detach callbackA, only + const resp = await ref.off('value', callbackA); + should(resp, undefined); + + // Trigger the event the callback is listening to + await ref.set(DatabaseContents.NEW.string); + + // Add a delay to ensure that the .set() has had time to be registered + await new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, 1000); + }); + + // CallbackB should still be attached + spyA.should.be.calledOnce(); + spyB.should.be.calledTwice(); + + // Teardown + should(ref.off('value', callbackB), undefined); + }); + + context('that has been added multiple times', () => { + it('must be called as many times completely remove', async () => { + // Setup + + const spyA = sinon.spy(); + let callbackA; + + const ref = firebase.native.database().ref('tests/types/string'); + + // Attach the callback the first time + await new Promise((resolve) => { + callbackA = () => { + spyA(); + resolve(); + }; + ref.on('value', callbackA); + }); + + // Attach the callback the second time + ref.on('value', callbackA); + + // Add a delay to ensure that the .on() has had time to be registered + await new Promise((resolve) => { + setTimeout(() => { + resolve(); + }, 1000); + }); + + spyA.should.be.calledTwice(); + + // Undo the first time the callback was attached + const resp = await ref.off('value', callbackA); + should(resp, undefined); + + // Trigger the event the callback is listening to + await ref.set(DatabaseContents.DEFAULT.number); + + // Callback should have been called only once because one of the attachments + // has been removed + // TODO: Android: There is definitely a single listener, but value is called twice + // rather than the once you'd perhaps expect + const expectedCount = Platform.OS === 'ios' ? 3 : 4; + spyA.should.be.callCount(expectedCount); + + // Undo the second attachment + const resp2 = await ref.off('value', callbackA); + should(resp2, undefined); + + // Trigger the event the callback is listening to + await ref.set(DatabaseContents.DEFAULT.number); + + // Callback should not have been called any more times + spyA.should.be.callCount(expectedCount); + }); + }); + }); + + xcontext('when a context', () => { + /** + * @todo Add tests for when a context is passed. Not sure what the intended + * behaviour is as the documentation is unclear, but assumption is that as the + * context is not required to unbind a listener, it's used as a filter parameter + * so in order for off() to remove a callback, the callback must have been bound + * with the same event type, callback function and context. + * + * Needs to be tested against web implementation, if possible. + */ + + }); + }); +} + +export default offTests; diff --git a/tests/src/tests/database/ref/onTests.js b/tests/src/tests/database/ref/onTests.js new file mode 100644 index 00000000..8f01708b --- /dev/null +++ b/tests/src/tests/database/ref/onTests.js @@ -0,0 +1,125 @@ +import sinon from 'sinon'; +import 'should-sinon'; +import Promise from 'bluebird'; + +import DatabaseContents from '../../support/DatabaseContents'; + +function onTests({ describe, it, firebase, tryCatch }) { + describe('ref().on()', () => { + it('calls callback when value changes', () => { + return Promise.each(Object.keys(DatabaseContents.DEFAULT), async (dataRef) => { + // Setup + + const ref = firebase.native.database().ref(`tests/types/${dataRef}`); + const currentDataValue = DatabaseContents.DEFAULT[dataRef]; + + const callback = sinon.spy(); + + // Test + + await new Promise((resolve) => { + ref.on('value', (snapshot) => { + callback(snapshot.val()); + resolve(); + }); + }); + + callback.should.be.calledWith(currentDataValue); + + const newDataValue = DatabaseContents.NEW[dataRef]; + await ref.set(newDataValue); + + // Assertions + + callback.should.be.calledWith(newDataValue); + + // Tear down + + ref.off(); + }); + }); + + it('allows binding multiple callbacks to the same ref', () => { + return Promise.each(Object.keys(DatabaseContents.DEFAULT), async (dataRef) => { + // Setup + + const ref = firebase.native.database().ref(`tests/types/${dataRef}`); + const currentDataValue = DatabaseContents.DEFAULT[dataRef]; + + const callbackA = sinon.spy(); + const callbackB = sinon.spy(); + + // Test + + await new Promise((resolve) => { + ref.on('value', (snapshot) => { + callbackA(snapshot.val()); + resolve(); + }); + }); + + await new Promise((resolve) => { + ref.on('value', (snapshot) => { + callbackB(snapshot.val()); + resolve(); + }); + }); + + callbackA.should.be.calledWith(currentDataValue); + callbackB.should.be.calledWith(currentDataValue); + + // Tear down + + ref.off(); + }); + }); + + it('calls callback with current values', () => { + return Promise.each(Object.keys(DatabaseContents.DEFAULT), (dataRef) => { + // Setup + + const dataTypeValue = DatabaseContents.DEFAULT[dataRef]; + const ref = firebase.native.database().ref(`tests/types/${dataRef}`); + + // Test + + return ref.on('value', (snapshot) => { + // Assertion + + snapshot.val().should.eql(dataTypeValue); + + // Tear down + + ref.off(); + }); + }); + }); + + it('errors if permission denied', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch(() => { + // Assertion + + reject(new Error('No permission denied error')); + }, reject); + + const failureCb = tryCatch((error) => { + // Assertion + + error.message.includes('permission_denied').should.be.true(); + resolve(); + }, reject); + + // Setup + + const invalidRef = firebase.native.database().ref('nope'); + + // Test + + invalidRef.on('value', successCb, failureCb); + }); + }); + }); +} + +export default onTests; diff --git a/tests/src/tests/database/ref/onceTests.js b/tests/src/tests/database/ref/onceTests.js new file mode 100644 index 00000000..6b5ee6b6 --- /dev/null +++ b/tests/src/tests/database/ref/onceTests.js @@ -0,0 +1,81 @@ +import sinon from 'sinon'; +import 'should-sinon'; + +import DatabaseContents from '../../support/DatabaseContents'; + +function onceTests({ describe, firebase, it, tryCatch }) { + describe('ref().once()', () => { + it('returns a promise', () => { + // Setup + + const ref = firebase.native.database().ref('tests/types/number'); + + // Test + + const returnValue = ref.once('value'); + + // Assertion + + returnValue.should.be.Promise(); + }); + + it('resolves with the correct value', async () => { + await Promise.map(Object.keys(DatabaseContents.DEFAULT), (dataRef) => { + // Setup + + const dataTypeValue = DatabaseContents.DEFAULT[dataRef]; + const ref = firebase.native.database().ref(`tests/types/${dataRef}`); + + // Test + + return ref.once('value').then((snapshot) => { + // Assertion + + snapshot.val().should.eql(dataTypeValue); + }); + }); + }); + + it('is NOT called when the value is changed', async () => { + // Setup + + const callback = sinon.spy(); + const ref = firebase.native.database().ref('tests/types/number'); + + // Test + + ref.once('value').then(callback); + + await ref.set(DatabaseContents.NEW.number); + + // Assertion + callback.should.be.calledOnce(); + }); + + it('errors if permission denied', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch(() => { + // Assertion + + reject(new Error('No permission denied error')); + }, reject); + + const failureCb = tryCatch((error) => { + // Assertion + + error.message.includes('permission_denied').should.be.true(); + resolve(); + }, reject); + + // Setup + + const reference = firebase.native.database().ref('nope'); + + // Test + reference.once('value', successCb, failureCb); + }); + }); + }); +} + +export default onceTests; diff --git a/tests/src/tests/database/ref/parentTests.js b/tests/src/tests/database/ref/parentTests.js new file mode 100644 index 00000000..95ec2d03 --- /dev/null +++ b/tests/src/tests/database/ref/parentTests.js @@ -0,0 +1,33 @@ +function parentTests({ describe, context, it, firebase }) { + describe('ref().parent', () => { + context('on the root ref', () => { + it('returns null', () => { + // Setup + + const ref = firebase.native.database().ref(); + + // Test + + + // Assertion + + (ref.parent === null).should.be.true(); + }); + }); + + context('on a non-root ref', () => { + it('returns correct parent', () => { + // Setup + + const ref = firebase.native.database().ref('tests/types/number'); + const parentRef = firebase.native.database().ref('tests/types'); + + // Assertion + + ref.parent.key.should.eql(parentRef.key); + }); + }); + }); +} + +export default parentTests; diff --git a/tests/src/tests/database/ref/pushTests.js b/tests/src/tests/database/ref/pushTests.js new file mode 100644 index 00000000..063ce35c --- /dev/null +++ b/tests/src/tests/database/ref/pushTests.js @@ -0,0 +1,113 @@ +import sinon from 'sinon'; +import 'should-sinon'; + +import DatabaseContents from '../../support/DatabaseContents'; + +function pushTests({ describe, it, firebase }) { + describe('ref().push()', () => { + it('returns a ref that can be used to set value later', async () => { + // Setup + + const ref = firebase.native.database().ref('tests/types/array'); + + let originalListValue; + + await ref.once('value', (snapshot) => { + originalListValue = snapshot.val(); + }); + + originalListValue.should.eql(DatabaseContents.DEFAULT.array); + + // Test + + const newItemRef = ref.push(); + + const valueToAddToList = DatabaseContents.NEW.number; + await newItemRef.set(valueToAddToList); + + let newItemValue, + newListValue; + + // Assertion + + await newItemRef.once('value', (snapshot) => { + newItemValue = snapshot.val(); + }); + + newItemValue.should.eql(valueToAddToList); + + await ref.once('value', (snapshot) => { + newListValue = snapshot.val(); + }); + + const originalListAsObject = originalListValue.reduce((memo, value, index) => { + memo[index] = value; + return memo; + }, {}); + + originalListAsObject[newItemRef.key] = valueToAddToList; + + newListValue.should.eql(originalListAsObject); + }); + + it('allows setting value immediately', async () => { + // Setup + + const ref = firebase.native.database().ref('tests/types/array'); + + let originalListValue; + + await ref.once('value', (snapshot) => { + originalListValue = snapshot.val(); + }); + + // Test + + const valueToAddToList = DatabaseContents.NEW.number; + const newItemRef = await ref.push(valueToAddToList); + + let newItemValue, + newListValue; + + // Assertion + + await newItemRef.once('value', (snapshot) => { + newItemValue = snapshot.val(); + }); + + newItemValue.should.eql(valueToAddToList); + + await ref.once('value', (snapshot) => { + newListValue = snapshot.val(); + }); + + const originalListAsObject = originalListValue.reduce((memo, value, index) => { + memo[index] = value; + return memo; + }, {}); + + originalListAsObject[newItemRef.key] = valueToAddToList; + + newListValue.should.eql(originalListAsObject); + }); + + it('calls an onComplete callback', async () => { + // Setup + + const callback = sinon.spy(); + + const ref = firebase.native.database().ref('tests/types/array'); + + // Test + + const valueToAddToList = DatabaseContents.NEW.number; + await ref.push(valueToAddToList, callback); + + // Assertion + + callback.should.be.calledWith(null); + }); + }) +} + +export default pushTests; diff --git a/tests/src/tests/database/ref/queryTests.js b/tests/src/tests/database/ref/queryTests.js new file mode 100644 index 00000000..5282fb97 --- /dev/null +++ b/tests/src/tests/database/ref/queryTests.js @@ -0,0 +1,25 @@ +import 'should-sinon'; +import Promise from 'bluebird'; + +function queryTests({ describe, it, firebase, tryCatch }) { + describe('ref query', () => { + it('orderByChild().equalTo()', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch((snapshot) => { + const webVal = snapshot.val(); + const ref = firebase.native.database().ref('tests/query'); + + ref.orderByChild('search').equalTo('foo').once('value', tryCatch((snapshot) => { + const nativeVal = snapshot.val(); + nativeVal.should.eql(webVal); + resolve(); + }, reject), reject); + }, reject); + + firebase.web.database().ref('tests/query').orderByChild('search').equalTo('foo').once('value', successCb, reject); + }); + }); + }); +} + +export default queryTests; diff --git a/tests/src/tests/database/ref/refTests.js b/tests/src/tests/database/ref/refTests.js new file mode 100644 index 00000000..7d3517ec --- /dev/null +++ b/tests/src/tests/database/ref/refTests.js @@ -0,0 +1,15 @@ +function refTests({ describe, it, firebase }) { + describe('ref().ref', () => { + it('returns a the reference itself', () => { + // Setup + + const ref = firebase.native.database().ref(); + + // Assertion + + ref.ref.should.eql(ref); + }); + }); +} + +export default refTests; diff --git a/tests/src/tests/database/ref/removeTests.js b/tests/src/tests/database/ref/removeTests.js new file mode 100644 index 00000000..701fecd2 --- /dev/null +++ b/tests/src/tests/database/ref/removeTests.js @@ -0,0 +1,44 @@ +import DatabaseContents from '../../support/DatabaseContents'; + +function removeTests({ describe, it, firebase }) { + describe('ref().remove()', () => { + it('returns a promise', () => { + // Setup + + const ref = firebase.native.database().ref('tests/types'); + + // Test + + const returnValue = ref.remove({ number: DatabaseContents.DEFAULT.number }); + + // Assertion + + returnValue.should.be.Promise(); + }); + + it('sets value to null', async () => { + await Promise.map(Object.keys(DatabaseContents.DEFAULT), async (dataRef) => { + // Setup + + const previousValue = DatabaseContents.DEFAULT[dataRef]; + const ref = firebase.native.database().ref(`tests/types/${dataRef}`); + + await ref.once('value').then((snapshot) => { + snapshot.val().should.eql(previousValue); + }); + + // Test + + await ref.remove(); + + // Assertion + + await ref.once('value').then((snapshot) => { + (snapshot.val() === null).should.be.true(); + }); + }); + }); + }); +} + +export default removeTests; diff --git a/tests/src/tests/database/ref/rootTests.js b/tests/src/tests/database/ref/rootTests.js new file mode 100644 index 00000000..53e1a35d --- /dev/null +++ b/tests/src/tests/database/ref/rootTests.js @@ -0,0 +1,36 @@ +function rootTests({ describe, it, context, firebase }) { + describe('ref().root', () => { + context('when called on a non-root reference', () => { + it('returns root ref', () => { + // Setup + + const rootRef = firebase.native.database().ref(); + const nonRootRef = firebase.native.database().ref('tests/types/number'); + + // Test + + + // Assertion + + nonRootRef.root.query.should.eql(rootRef.query); + }); + }); + + context('when called on the root reference', () => { + it('returns root ref', () => { + // Setup + + const rootRef = firebase.native.database().ref(); + + // Test + + + // Assertion + + rootRef.root.query.should.eql(rootRef.query); + }); + }); + }); +} + +export default rootTests; diff --git a/tests/src/tests/database/ref/setTests.js b/tests/src/tests/database/ref/setTests.js new file mode 100644 index 00000000..1275664f --- /dev/null +++ b/tests/src/tests/database/ref/setTests.js @@ -0,0 +1,73 @@ +import DatabaseContents from '../../support/DatabaseContents'; + +function setTests({ describe, it, xit, firebase }) { + describe('ref.set()', () => { + xit('returns a promise', async () => { + // Setup + + const ref = firebase.native.database().ref('tests/types/number'); + + // Test + + const returnValue = ref.set(DatabaseContents.DEFAULT.number); + + // Assertion + + returnValue.should.be.Promise(); + + await returnValue.then((value) => { + (value === undefined).should.be.true(); + }); + }); + + it('changes value', async () => { + await Promise.map(Object.keys(DatabaseContents.DEFAULT), async (dataRef) => { + // Setup + + const previousValue = DatabaseContents.DEFAULT[dataRef]; + const ref = firebase.native.database().ref(`tests/types/${dataRef}`); + + await ref.once('value').then((snapshot) => { + snapshot.val().should.eql(previousValue); + }); + + const newValue = DatabaseContents.NEW[dataRef]; + + // Test + + await ref.set(newValue); + + await ref.once('value').then((snapshot) => { + // Assertion + + snapshot.val().should.eql(newValue); + }); + }); + }); + + it('can unset values', async () => { + await Promise.map(Object.keys(DatabaseContents.DEFAULT), async (dataRef) => { + // Setup + + const previousValue = DatabaseContents.DEFAULT[dataRef]; + const ref = firebase.native.database().ref(`tests/types/${dataRef}`); + + await ref.once('value').then((snapshot) => { + snapshot.val().should.eql(previousValue); + }); + + // Test + + await ref.set(null); + + await ref.once('value').then((snapshot) => { + // Assertion + + (snapshot.val() === null).should.be.true(); + }); + }); + }); + }); +} + +export default setTests; diff --git a/tests/src/tests/database/ref/transactionTests.js b/tests/src/tests/database/ref/transactionTests.js new file mode 100644 index 00000000..f37682b0 --- /dev/null +++ b/tests/src/tests/database/ref/transactionTests.js @@ -0,0 +1,53 @@ +import Promise from 'bluebird'; + +function onTests({ describe, it, firebase, tryCatch }) { + describe('ref.transaction()', () => { + it('works', () => { + return new Promise((resolve, reject) => { + let valueBefore = 1; + + firebase.native.database() + .ref('tests/transaction').transaction((currentData) => { + if (currentData === null) { + return valueBefore + 10; + } + valueBefore = currentData; + return valueBefore + 10; + }, tryCatch((error, committed, snapshot) => { + if (error) { + return reject(error); + } + + if (!committed) { + return reject(new Error('Transaction did not commit.')); + } + + snapshot.val().should.equal(valueBefore + 10); + + return resolve(); + }, reject), true); + }); + }); + + it('aborts if undefined returned', () => { + return new Promise((resolve, reject) => { + firebase.native.database() + .ref('tests/transaction').transaction(() => { + return undefined; + }, (error, committed) => { + if (error) { + return reject(error); + } + + if (!committed) { + return resolve(); + } + + return reject(new Error('Transaction did not abort commit.')); + }, true); + }); + }); + }); +} + +export default onTests; diff --git a/tests/src/tests/database/ref/updateTests.js b/tests/src/tests/database/ref/updateTests.js new file mode 100644 index 00000000..09af4383 --- /dev/null +++ b/tests/src/tests/database/ref/updateTests.js @@ -0,0 +1,112 @@ +import Promise from 'bluebird'; +import DatabaseContents from '../../support/DatabaseContents'; + +function updateTests({ describe, it, firebase }) { + describe('ref().update()', () => { + it('returns a promise', () => { + // Setup + + const ref = firebase.native.database().ref('tests/types'); + + // Test + + const returnValue = ref.update({ number: DatabaseContents.DEFAULT.number }); + + // Assertion + + returnValue.should.be.Promise(); + }); + + it('changes value', () => { + return Promise.each(Object.keys(DatabaseContents.DEFAULT), async (dataRef) => { + // Setup + + const previousValue = DatabaseContents.DEFAULT[dataRef]; + const ref = firebase.native.database().ref(`tests/types/${dataRef}`); + + await ref.once('value').then((snapshot) => { + snapshot.val().should.eql(previousValue); + }); + + const newValue = DatabaseContents.NEW[dataRef]; + const parentRef = firebase.native.database().ref('tests/types'); + + // Test + + await parentRef.update({ [dataRef]: newValue }); + + // Assertion + + await ref.once('value').then((snapshot) => { + snapshot.val().should.eql(newValue); + }); + }); + }); + + it('can unset values', () => { + return Promise.each(Object.keys(DatabaseContents.DEFAULT), async (dataRef) => { + // Setup + + const previousValue = DatabaseContents.DEFAULT[dataRef]; + const ref = firebase.native.database().ref(`tests/types/${dataRef}`); + + await ref.once('value').then((snapshot) => { + snapshot.val().should.eql(previousValue); + }); + + const parentRef = firebase.native.database().ref('tests/types'); + + // Test + + await parentRef.update({ [dataRef]: null }); + + // Assertion + + await ref.once('value').then((snapshot) => { + (snapshot.val() === null).should.be.true(); + }); + }); + }); + + it('updates multiple values at once', async () => { + // Setup + + const numberPreviousValue = DatabaseContents.DEFAULT.number; + const stringPreviousValue = DatabaseContents.DEFAULT.string; + + const numberRef = firebase.native.database().ref('tests/types/number'); + const stringRef = firebase.native.database().ref('tests/types/string'); + + await numberRef.once('value').then((snapshot) => { + snapshot.val().should.eql(numberPreviousValue); + }); + + await stringRef.once('value').then((snapshot) => { + snapshot.val().should.eql(stringPreviousValue); + }); + + const numberNewValue = DatabaseContents.NEW.number; + const stringNewValue = DatabaseContents.NEW.string; + const parentRef = firebase.native.database().ref('tests/types'); + + // Test + + await parentRef.update({ + number: numberNewValue, + string: stringNewValue, + }); + + // Assertion + + await numberRef.once('value').then((snapshot) => { + snapshot.val().should.eql(numberNewValue); + }); + + await stringRef.once('value').then((snapshot) => { + snapshot.val().should.eql(stringNewValue); + }); + }); + }); +} + +export default updateTests; diff --git a/tests/src/tests/database/snapshot.js b/tests/src/tests/database/snapshot.js new file mode 100644 index 00000000..04dc5940 --- /dev/null +++ b/tests/src/tests/database/snapshot.js @@ -0,0 +1,116 @@ +export default function addTests({ tryCatch, describe, it, firebase }) { + describe('Snapshot', () => { + it('should provide a functioning val() method', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch((snapshot) => { + snapshot.val.should.be.a.Function(); + snapshot.val().should.eql([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + ]); + resolve(); + }, reject); + + firebase.native.database().ref('tests/types/array').once('value', successCb, reject); + }); + }); + + it('should provide a functioning child() method', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch((snapshot) => { + snapshot.child('0').val.should.be.a.Function(); + snapshot.child('0').val().should.equal(0); + snapshot.child('0').key.should.be.a.String(); + snapshot.child('0').key.should.equal('0'); + resolve(); + }, reject); + + firebase.native.database().ref('tests/types/array').once('value', successCb, reject); + }); + }); + + it('should provide a functioning hasChild() method', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch((snapshot) => { + snapshot.hasChild.should.be.a.Function(); + snapshot.hasChild('foo').should.equal(true); + snapshot.hasChild('baz').should.equal(false); + resolve(); + }, reject); + + firebase.native.database().ref('tests/types/object').once('value', successCb, reject); + }); + }); + + it('should provide a functioning hasChildren() method', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch((snapshot) => { + snapshot.hasChildren.should.be.a.Function(); + snapshot.hasChildren().should.equal(true); + snapshot.child('foo').hasChildren().should.equal(false); + resolve(); + }, reject); + + firebase.native.database().ref('tests/types/object').once('value', successCb, reject); + }); + }); + + it('should provide a functioning exists() method', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch((snapshot) => { + snapshot.exists.should.be.a.Function(); + snapshot.exists().should.equal(false); + resolve(); + }, reject); + + firebase.native.database().ref('tests/types/object/baz/daz').once('value', successCb, reject); + }); + }); + + it('should provide a functioning getPriority() method', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch((snapshot) => { + snapshot.getPriority.should.be.a.Function(); + snapshot.getPriority().should.equal(666); + snapshot.val().should.eql({ foo: 'bar' }); + resolve(); + }, reject); + + const ref = firebase.native.database().ref('tests/priority'); + ref.once('value', successCb, reject); + }); + }); + + it('should provide a functioning forEach() method', () => { + // TODO this doesn't really test that the key order returned is in correct order + return new Promise((resolve, reject) => { + const successCb = tryCatch((snapshot) => { + let total = 0; + snapshot.forEach.should.be.a.Function(); + snapshot.forEach((childSnapshot) => { + const val = childSnapshot.val(); + total = total + val; + return val === 3; // stop iteration after key 3 + }); + + total.should.equal(6); // 0 + 1 + 2 + 3 = 6 + resolve(); + }, reject); + + firebase.native.database().ref('tests/types/array').once('value', successCb, reject); + }); + }); + + it('should provide a key property', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch((snapshot) => { + snapshot.key.should.be.a.String(); + snapshot.key.should.equal('array'); + resolve(); + }, reject); + + firebase.native.database().ref('tests/types/array').once('value', successCb, reject); + }); + }); + }); + +} diff --git a/tests/src/tests/index.js b/tests/src/tests/index.js new file mode 100644 index 00000000..806f411e --- /dev/null +++ b/tests/src/tests/index.js @@ -0,0 +1,216 @@ +import { setSuiteStatus, setTestStatus } from '../actions/TestActions'; +import analytics from './analytics/index'; +import crash from './crash/index'; +import database from './database/index'; +import messaging from './messaging/index'; +import storage from './storage/index'; +import auth from './auth/index'; + +const testSuiteInstances = [ + database, + auth, + analytics, + messaging, + crash, + storage, +]; + +/* + A map of test suite instances to their ids so they may be retrieved + at run time and called upon to run individual tests + */ +const testSuiteRunners = {}; + +/* + Attributes to hold initial Redux store state + */ +const testSuites = {}; +const tests = {}; +const focusedTestIds = {}; +const pendingTestIds = {}; +const testContexts = {}; + +/** + * @typedef {number} TestId + * @typedef {number} TestSuiteId + * + * @typedef {Object} Test + * @property {number} id + * @property {number} testSuiteId + * + * @typedef {Object} TestSuite + * @property {number} id + * @property {TestId[]} testIds + * + * @typedef {Object.} IndexedTestGroup + * @typedef {Object.} IndexedTestSuiteGroup + * @typedef {Object.} IdLookup + */ + +/** + * Return initial state for the tests to provide to Redux + * @returns {{suites: {}, descriptions: {}}} + */ +export function initialState() { + testSuiteInstances.forEach((testSuite) => { + const { id, name, description } = testSuite; + + // Add to test suite runners for later recall + testSuiteRunners[testSuite.id] = testSuite; + + const testDefinitions = testSuite.testDefinitions; + + // Add to test suites to place in the redux store + testSuites[testSuite.id] = { + id, + name, + description, + + testContextIds: Object.keys(testDefinitions.testContexts), + testIds: Object.keys(testDefinitions.tests), + + status: null, + message: null, + time: 0, + progress: 0, + }; + + Object.assign(tests, testDefinitions.tests); + Object.assign(testContexts, testDefinitions.testContexts); + Object.assign(focusedTestIds, testDefinitions.focusedTestIds); + Object.assign(pendingTestIds, testDefinitions.pendingTestIds); + }); + + return { + tests, + testSuites, + testContexts, + focusedTestIds, + pendingTestIds, + }; +} + +/** + * Provide a redux store to the test suites + * @param store + */ +export function setupSuites(store) { + Object.values(testSuiteRunners).forEach((testSuite) => { + // eslint-disable-next-line no-param-reassign + testSuite.setStore(store, (action) => { + store.dispatch(setSuiteStatus(action)); + }, (action) => { + store.dispatch(setTestStatus(action)); + }); + }); +} + +/** + * Run a single test by id, ignoring whether it's pending or focused. + * @param {number} testId - id of test to run + */ +export function runTest(testId) { + const test = tests[testId]; + + runTests({ [testId]: test }); +} + +/** + * Run all tests in all test suites. If testIds is provided, only run the tests + * that match the ids included. + * @params {IndexedTestGroup} testGroup - Group of tests to run + * @param {Object=} options - options limiting which tests should be run + * @param {IdLookup} options.pendingTestIds - map of ids of pending tests + * @param {IdLookup} options.focusedTestIds - map of ids of focused tests + */ +export function runTests(testGroup, options = { pendingTestIds: {}, focusedTestIds: {} }) { + const areFocusedTests = Object.keys(options.focusedTestIds).length > 0; + + if (areFocusedTests) { + runOnlyTestsInLookup(testGroup, options.focusedTestIds); + } else { + const arePendingTests = Object.keys(options.pendingTestIds).length > 0; + + if (arePendingTests) { + runAllButTestsInLookup(testGroup, options.pendingTestIds); + } else { + const testsBySuiteId = getTestsBySuiteId(testGroup); + runTestsBySuiteId(testsBySuiteId); + } + } +} + +/** + * Runs all tests listed in tests, except those with ids matching values in + * testLookup + * @param {IndexedTestGroup} testGroup - complete list of tests + * @param {IdLookup} testLookup - id lookup of pending tests + */ +function runAllButTestsInLookup(testGroup, testLookup) { + const testsToRunBySuiteId = Object.keys(testGroup).reduce((memo, testId) => { + const testIsNotPending = !testLookup[testId]; + + if (testIsNotPending) { + const test = testGroup[testId]; + // eslint-disable-next-line no-param-reassign + memo[test.testSuiteId] = memo[test.testSuiteId] || []; + memo[test.testSuiteId].push(testId); + } + + return memo; + }, {}); + + Promise.each(Object.keys(testsToRunBySuiteId), (testSuiteId) => { + const testIds = testsToRunBySuiteId[testSuiteId]; + return runSuite(testSuiteId, testIds); + }); +} + +/** + * Runs only the tests listed in focused tests + * @param {IndexedTestGroup} testGroup - complete list of tests + * @param {IdLookup} testLookup - id lookup of focused tests + */ +function runOnlyTestsInLookup(testGroup, testLookup) { + const testsInLookupBySuiteId = getTestsBySuiteId(testGroup, testLookup); + runTestsBySuiteId(testsInLookupBySuiteId); +} + +function runTestsBySuiteId(suiteIdTests) { + Promise.each(Object.keys(suiteIdTests), (testSuiteId) => { + const testIds = suiteIdTests[testSuiteId]; + + return runSuite(testSuiteId, testIds); + }); +} + +/** + * Run tests in a suite. If testIds is provided, only run the tests that match the + * ids included. + * @param {number} testSuiteId - Id of test suite to run + * @param {number[]=} testIds - array of test ids to run from the test suite + */ +function runSuite(testSuiteId, testIds = null) { + const testSuiteRunner = testSuiteRunners[testSuiteId]; + + if (testSuiteRunner) { + return testSuiteRunner.run(testIds); + } + + console.error(`runSuite: Suite with id "${testSuiteId}" not found`); + return Promise.reject(); +} + +function getTestsBySuiteId(testGroup, testLookup = testGroup) { + return Object.keys(testLookup).reduce((memo, testId) => { + const test = testGroup[testId]; + + if (test) { + // eslint-disable-next-line no-param-reassign + memo[test.testSuiteId] = memo[test.testSuiteId] || []; + memo[test.testSuiteId].push(testId); + } + + return memo; + }, {}); +} diff --git a/tests/src/tests/messaging/index.js b/tests/src/tests/messaging/index.js new file mode 100644 index 00000000..ee8ba50a --- /dev/null +++ b/tests/src/tests/messaging/index.js @@ -0,0 +1,10 @@ +import firebase from '../../firebase'; +import TestSuite from '../../../lib/TestSuite'; + +import messagingTests from './messagingTests'; + +const suite = new TestSuite('Messaging', 'firebase.messaging()', firebase); + +suite.addTests(messagingTests); + +export default suite; diff --git a/tests/src/tests/messaging/messagingTests.js b/tests/src/tests/messaging/messagingTests.js new file mode 100644 index 00000000..fa5ae579 --- /dev/null +++ b/tests/src/tests/messaging/messagingTests.js @@ -0,0 +1,149 @@ +function messagingTests({ describe, it, firebase }) { + describe('FCM', () => { + it('it should build a RemoteMessage', () => { + const remoteMessage = new firebase.native.messaging.RemoteMessage('305229645282'); + + // all optional + remoteMessage.setId('foobar'); + remoteMessage.setTtl(12000); + remoteMessage.setType('something'); + remoteMessage.setData({ + object: { foo: 'bar ' }, + array: [1, 2, 3, 4, 5], + string: 'hello', + boolean: true, + number: 123456, + }); + + // return json object so we can assert values + const mOutput = remoteMessage.toJSON(); + + mOutput.id.should.equal('foobar'); + mOutput.ttl.should.equal(12000); + mOutput.type.should.equal('something'); + mOutput.data.should.be.a.Object(); + + // all data types should be a string as this is all that native accepts + mOutput.data.object.should.equal('[object Object]'); + mOutput.data.array.should.equal('1,2,3,4,5'); + mOutput.data.string.should.equal('hello'); + mOutput.data.number.should.equal('123456'); + + return Promise.resolve(); + }); + + it('should send a RemoteMessage', () => { + const remoteMessage = new firebase.native.messaging.RemoteMessage('305229645282'); + + // all optional + remoteMessage.setId('foobar'); + remoteMessage.setTtl(12000); + remoteMessage.setType('something'); + remoteMessage.setData({ + object: { foo: 'bar ' }, + array: [1, 2, 3, 4, 5], + string: 'hello', + number: 123456, + }); + + firebase.native.messaging().send(remoteMessage); + return Promise.resolve(); + }); + + it('it should return fcm token from getToken', () => { + const successCb = (token) => { + console.log(token); + token.should.be.a.String(); + return Promise.resolve(); + }; + + return firebase.native.messaging() + .getToken() + .then(successCb); + }); + + it('it should build a RemoteMessage', () => { + const remoteMessage = new firebase.native.messaging.RemoteMessage('305229645282'); + + // all optional + remoteMessage.setId('foobar'); + remoteMessage.setTtl(12000); + remoteMessage.setType('something'); + remoteMessage.setData({ + object: { foo: 'bar ' }, + array: [1, 2, 3, 4, 5], + string: 'hello', + boolean: true, + number: 123456, + }); + + // return json object so we can assert values + const mOutput = remoteMessage.toJSON(); + + mOutput.id.should.equal('foobar'); + mOutput.ttl.should.equal(12000); + mOutput.type.should.equal('something'); + mOutput.data.should.be.a.Object(); + + // all data types should be a string as this is all that native accepts + mOutput.data.object.should.equal('[object Object]'); + mOutput.data.array.should.equal('1,2,3,4,5'); + mOutput.data.string.should.equal('hello'); + mOutput.data.number.should.equal('123456'); + + return Promise.resolve(); + }); + + + it('it should send a RemoteMessage', () => { + const remoteMessage = new firebase.native.messaging.RemoteMessage('305229645282'); + + // all optional + remoteMessage.setId('foobar'); + remoteMessage.setTtl(12000); + remoteMessage.setType('something'); + remoteMessage.setData({ + object: { foo: 'bar ' }, + array: [1, 2, 3, 4, 5], + string: 'hello', + number: 123456, + }); + + firebase.native.messaging().send(remoteMessage); + return Promise.resolve(); + }); + + it('it should create/remove onTokenRefresh listeners', () => { + const cb = () => { + }; + try { + const listener = firebase.native.messaging().onTokenRefresh(cb); + listener.remove(); + } catch (e) { + console.error(e); + } + + return Promise.resolve(); + }); + + it('it should subscribe/unsubscribe to topics', () => { + firebase.native.messaging().subscribeToTopic('foobar'); + firebase.native.messaging().unsubscribeFromTopic('foobar'); + return Promise.resolve(); + }); + + it('it should show a notification', () => { + firebase.native.messaging().createLocalNotification({ + title: 'Hello', + body: 'My Notification Message', + big_text: "Is it me you're looking for?", + sub_text: 'nope', + show_in_foreground: true, + }); + + return Promise.resolve(); + }); + }); +} + +export default messagingTests; diff --git a/tests/src/tests/storage/index.js b/tests/src/tests/storage/index.js new file mode 100644 index 00000000..62a745e7 --- /dev/null +++ b/tests/src/tests/storage/index.js @@ -0,0 +1,10 @@ +import firebase from '../../firebase'; +import TestSuite from '../../../lib/TestSuite'; +import storageTests from './storageTests'; + +const suite = new TestSuite('Storage', 'Upload/Download storage tests', firebase); + +suite.addTests(storageTests); + +export default suite; + diff --git a/tests/src/tests/storage/storageTests.js b/tests/src/tests/storage/storageTests.js new file mode 100644 index 00000000..104b27e9 --- /dev/null +++ b/tests/src/tests/storage/storageTests.js @@ -0,0 +1,90 @@ +function storageTests({ xdescribe, it, firebase, tryCatch }) { + xdescribe('downloadFile()', () => { + it('it should error on download file if permission denied', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch(() => { + reject(new Error('No permission denied error')); + }, reject); + + const failureCb = tryCatch((error) => { + error.code.should.equal('storage/unauthorized'); + error.message.includes('not authorized').should.be.true(); + resolve(); + }, reject); + + firebase.native.storage().ref('/not.jpg').downloadFile(`${firebase.native.storage.Native.DOCUMENT_DIRECTORY_PATH}/not.jpg`).then(successCb).catch(failureCb); + }); + }); + + it('it should download a file', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch((meta) => { + meta.state.should.eql(firebase.native.storage.TaskState.SUCCESS); + meta.bytesTransferred.should.eql(meta.totalBytes); + resolve(); + }, reject); + + const failureCb = tryCatch((error) => { + reject(error); + }, reject); + + firebase.native.storage().ref('/ok.jpeg').downloadFile(`${firebase.native.storage.Native.DOCUMENT_DIRECTORY_PATH}/ok.jpeg`).then(successCb).catch(failureCb); + }); + }); + }); + + xdescribe('putFile()', () => { + it('it should error on upload if permission denied', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch(() => { + reject(new Error('No permission denied error')); + }, reject); + + const failureCb = tryCatch((error) => { + error.code.should.equal('storage/unauthorized'); + error.message.includes('not authorized').should.be.true(); + resolve(); + }, reject); + + firebase.native.storage().ref('/uploadNope.jpeg').putFile(`${firebase.native.storage.Native.DOCUMENT_DIRECTORY_PATH}/ok.jpeg`).then(successCb).catch(failureCb); + }); + }); + + it('it should upload a file', () => { + return new Promise((resolve, reject) => { + const successCb = tryCatch((uploadTaskSnapshot) => { + uploadTaskSnapshot.state.should.eql(firebase.native.storage.TaskState.SUCCESS); + uploadTaskSnapshot.bytesTransferred.should.eql(uploadTaskSnapshot.totalBytes); + uploadTaskSnapshot.metadata.should.be.an.Object(); + uploadTaskSnapshot.downloadUrl.should.be.a.String(); + resolve(); + }, reject); + + const failureCb = tryCatch((error) => { + reject(error); + }, reject); + + firebase.native.storage().ref('/uploadOk.jpeg').putFile(`${firebase.native.storage.Native.DOCUMENT_DIRECTORY_PATH}/ok.jpeg`).then(successCb).catch(failureCb); + }); + }); + }); + + xdescribe('on()', () => { + it('should listen to upload state', () => { + return new Promise((resolve, reject) => { + const path = `${firebase.native.storage.Native.DOCUMENT_DIRECTORY_PATH}/ok.jpeg`; + const ref = firebase.native.storage().ref('/uploadOk.jpeg'); + const unsubscribe = ref.putFile(path).on(firebase.native.storage.TaskEvent.STATE_CHANGED, tryCatch((snapshot) => { + if (snapshot.state === firebase.native.storage.TaskState.SUCCESS) { + resolve(); + } + }, reject), tryCatch((error) => { + unsubscribe(); + reject(error); + }, reject)); + }); + }); + }); +} + +export default storageTests; diff --git a/tests/src/tests/support/DatabaseContents.js b/tests/src/tests/support/DatabaseContents.js new file mode 100644 index 00000000..0f786cd5 --- /dev/null +++ b/tests/src/tests/support/DatabaseContents.js @@ -0,0 +1,25 @@ +export default { + DEFAULT: { + array: [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + ], + boolean: true, + string: 'foobar', + number: 123567890, + object: { + foo: 'bar', + }, + }, + + NEW: { + array: [ + 9, 8, 7, 6, 5, 4, + ], + boolean: false, + string: 'baz', + number: 84564564, + object: { + foo: 'baz', + }, + }, +}; diff --git a/tests/src/tests/support/databaseTypeMap.js b/tests/src/tests/support/databaseTypeMap.js new file mode 100644 index 00000000..8cbacf12 --- /dev/null +++ b/tests/src/tests/support/databaseTypeMap.js @@ -0,0 +1,10 @@ +import DatabaseContents from './DatabaseContents'; + +const databaseTypeMap = + Object.keys(DatabaseContents.DEFAULT).reduce((dataTypeMap, dataType) => { + // eslint-disable-next-line no-param-reassign + dataTypeMap[`tests/types/${dataType}`] = DatabaseContents.DEFAULT[dataType]; + return dataTypeMap; + }, {}); + +export default databaseTypeMap;