commit
a87a04da0c
|
@ -14,16 +14,19 @@ xcuserdata/
|
||||||
# Android
|
# Android
|
||||||
|
|
||||||
# Built application files
|
# Built application files
|
||||||
android/*/build/
|
**/android/**/build/
|
||||||
|
|
||||||
# Crashlytics configuations
|
# Crashlytics configuations
|
||||||
android/com_crashlytics_export_strings.xml
|
android/com_crashlytics_export_strings.xml
|
||||||
|
|
||||||
|
# Signing files
|
||||||
|
android/.signing/
|
||||||
|
|
||||||
# Local configuration file (sdk path, etc)
|
# Local configuration file (sdk path, etc)
|
||||||
android/local.properties
|
**/android/local.properties
|
||||||
|
|
||||||
# Gradle generated files
|
# Gradle generated files
|
||||||
android/.gradle/
|
**/android/.gradle/
|
||||||
|
|
||||||
# Signing files
|
# Signing files
|
||||||
android/.signing/
|
android/.signing/
|
||||||
|
@ -41,7 +44,7 @@ android/.idea/misc.xml
|
||||||
android/.idea/modules.xml
|
android/.idea/modules.xml
|
||||||
android/.idea/scopes/scope_settings.xml
|
android/.idea/scopes/scope_settings.xml
|
||||||
android/.idea/vcs.xml
|
android/.idea/vcs.xml
|
||||||
android/*.iml
|
**/android/**/*.iml
|
||||||
ios/RnFirebase.xcodeproj/xcuserdata
|
ios/RnFirebase.xcodeproj/xcuserdata
|
||||||
|
|
||||||
# OS-specific files
|
# OS-specific files
|
||||||
|
@ -54,9 +57,24 @@ ehthumbs.db
|
||||||
Thumbs.dbandroid/gradle
|
Thumbs.dbandroid/gradle
|
||||||
android/gradlew
|
android/gradlew
|
||||||
android/build
|
android/build
|
||||||
|
android/.gradle
|
||||||
android/gradlew.bat
|
android/gradlew.bat
|
||||||
android/gradle/
|
android/gradle
|
||||||
.idea
|
lib/.watchmanconfig
|
||||||
.idea
|
.idea
|
||||||
coverage
|
coverage
|
||||||
yarn.lock
|
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/
|
||||||
|
|
||||||
|
|
|
@ -60,3 +60,6 @@ docs
|
||||||
.idea
|
.idea
|
||||||
coverage
|
coverage
|
||||||
yarn.lock
|
yarn.lock
|
||||||
|
tests
|
||||||
|
lib/.watchmanconfig
|
||||||
|
|
||||||
|
|
51
README.md
51
README.md
|
@ -1,4 +1,4 @@
|
||||||
# React Native Firebase<img align="left" src="http://i.imgur.com/01XQL0x.png">
|
# React Native Firebase<a href="https://invertase.io/react-native-firebase"><img align="left" src="http://i.imgur.com/01XQL0x.png"></a>
|
||||||
|
|
||||||
[![Chat](https://img.shields.io/badge/chat-on%20discord-7289da.svg)](https://discord.gg/t6bdqMs)
|
[![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)
|
[![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)
|
[![License](https://img.shields.io/npm/l/react-native-firebase.svg)](/LICENSE)
|
||||||
|
|
||||||
**RNFirebase** makes using [Firebase](http://firebase.com) with React Native simple.
|
**RNFirebase** makes using [Firebase](http://firebase.com) with React Native simple.
|
||||||
|
|
||||||
|
> [Documentation](https://invertase.io/react-native-firebase)
|
||||||
|
|
||||||
|
|
||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
### Install
|
### Install
|
||||||
```
|
```bash
|
||||||
npm i react-native-firebase --save
|
npm i react-native-firebase --save
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Platform specific setup guides:
|
#### 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)
|
||||||
|
|
||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
|
@ -30,47 +34,6 @@ The native SDKs also allow us to hook into device sdk's which are not possible w
|
||||||
|
|
||||||
<hr>
|
<hr>
|
||||||
|
|
||||||
### 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.
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
### 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.
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
### 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)
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
### 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
|
|
||||||
|
|
||||||
<hr>
|
|
||||||
|
|
||||||
### License
|
### License
|
||||||
|
|
||||||
- MIT
|
- MIT
|
||||||
|
|
|
@ -6,7 +6,7 @@ Pod::Spec.new do |s|
|
||||||
s.version = package["version"]
|
s.version = package["version"]
|
||||||
s.summary = package["description"]
|
s.summary = package["description"]
|
||||||
s.description = <<-DESC
|
s.description = <<-DESC
|
||||||
Wanna integrate firebase into your app using React Native?
|
Integrate firebase into your app using the React Native SDKs.
|
||||||
DESC
|
DESC
|
||||||
s.homepage = "http://invertase.io"
|
s.homepage = "http://invertase.io"
|
||||||
s.license = package['license']
|
s.license = package['license']
|
||||||
|
@ -16,11 +16,4 @@ Pod::Spec.new do |s|
|
||||||
s.platform = :ios, "8.0"
|
s.platform = :ios, "8.0"
|
||||||
s.preserve_paths = 'README.md', 'package.json', '*.js'
|
s.preserve_paths = 'README.md', 'package.json', '*.js'
|
||||||
s.source_files = 'ios/RNFirebase/*.{h,m}'
|
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
|
end
|
||||||
|
|
|
@ -78,12 +78,13 @@ public class Utils {
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param name
|
* @param name
|
||||||
|
* @param refId
|
||||||
|
* @param listenerId
|
||||||
* @param path
|
* @param path
|
||||||
* @param modifiersString
|
|
||||||
* @param dataSnapshot
|
* @param dataSnapshot
|
||||||
* @return
|
* @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 snapshot = Arguments.createMap();
|
||||||
WritableMap eventMap = Arguments.createMap();
|
WritableMap eventMap = Arguments.createMap();
|
||||||
|
|
||||||
|
@ -106,10 +107,13 @@ public class Utils {
|
||||||
snapshot.putArray("childKeys", Utils.getChildKeys(dataSnapshot));
|
snapshot.putArray("childKeys", Utils.getChildKeys(dataSnapshot));
|
||||||
mapPutValue("priority", dataSnapshot.getPriority(), snapshot);
|
mapPutValue("priority", dataSnapshot.getPriority(), snapshot);
|
||||||
|
|
||||||
|
eventMap.putInt("refId", refId);
|
||||||
|
if (listenerId != null) {
|
||||||
|
eventMap.putInt("listenerId", listenerId);
|
||||||
|
}
|
||||||
eventMap.putString("path", path);
|
eventMap.putString("path", path);
|
||||||
eventMap.putMap("snapshot", snapshot);
|
eventMap.putMap("snapshot", snapshot);
|
||||||
eventMap.putString("eventName", name);
|
eventMap.putString("eventName", name);
|
||||||
eventMap.putString("modifiersString", modifiersString);
|
|
||||||
|
|
||||||
return eventMap;
|
return eventMap;
|
||||||
}
|
}
|
||||||
|
|
|
@ -34,7 +34,7 @@ import io.invertase.firebase.Utils;
|
||||||
|
|
||||||
public class RNFirebaseDatabase extends ReactContextBaseJavaModule {
|
public class RNFirebaseDatabase extends ReactContextBaseJavaModule {
|
||||||
private static final String TAG = "RNFirebaseDatabase";
|
private static final String TAG = "RNFirebaseDatabase";
|
||||||
private HashMap<String, RNFirebaseDatabaseReference> mDBListeners = new HashMap<>();
|
private HashMap<Integer, RNFirebaseDatabaseReference> mReferences = new HashMap<>();
|
||||||
private HashMap<String, RNFirebaseTransactionHandler> mTransactionHandlers = new HashMap<>();
|
private HashMap<String, RNFirebaseTransactionHandler> mTransactionHandlers = new HashMap<>();
|
||||||
private FirebaseDatabase mFirebaseDatabase;
|
private FirebaseDatabase mFirebaseDatabase;
|
||||||
|
|
||||||
|
@ -279,61 +279,60 @@ public class RNFirebaseDatabase extends ReactContextBaseJavaModule {
|
||||||
}
|
}
|
||||||
|
|
||||||
@ReactMethod
|
@ReactMethod
|
||||||
public void on(final String path, final String modifiersString, final ReadableArray modifiersArray, final String eventName, final Callback callback) {
|
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(path, modifiersArray, modifiersString);
|
RNFirebaseDatabaseReference ref = this.getDBHandle(refId, path, modifiers);
|
||||||
|
|
||||||
if (eventName.equals("value")) {
|
if (eventName.equals("value")) {
|
||||||
ref.addValueEventListener();
|
ref.addValueEventListener(listenerId);
|
||||||
} else {
|
} else {
|
||||||
ref.addChildEventListener(eventName);
|
ref.addChildEventListener(listenerId, eventName);
|
||||||
}
|
}
|
||||||
|
|
||||||
WritableMap resp = Arguments.createMap();
|
WritableMap resp = Arguments.createMap();
|
||||||
resp.putString("status", "success");
|
resp.putString("status", "success");
|
||||||
|
resp.putInt("refId", refId);
|
||||||
resp.putString("handle", path);
|
resp.putString("handle", path);
|
||||||
callback.invoke(null, resp);
|
callback.invoke(null, resp);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ReactMethod
|
@ReactMethod
|
||||||
public void once(final String path, final String modifiersString, final ReadableArray modifiersArray, final String eventName, final Callback callback) {
|
public void once(final int refId, final String path, final ReadableArray modifiers, final String eventName, final Callback callback) {
|
||||||
RNFirebaseDatabaseReference ref = this.getDBHandle(path, modifiersArray, modifiersString);
|
RNFirebaseDatabaseReference ref = this.getDBHandle(refId, path, modifiers);
|
||||||
ref.addOnceValueEventListener(callback);
|
ref.addOnceValueEventListener(callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* At the time of this writing, off() only gets called when there are no more subscribers to a given path.
|
* 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.
|
* it doesn't really matter- just polluting the RN bridge a little more than necessary.
|
||||||
* off() should therefore clean *everything* up
|
* off() should therefore clean *everything* up
|
||||||
*/
|
*/
|
||||||
@ReactMethod
|
@ReactMethod
|
||||||
public void off(
|
public void off(
|
||||||
final String path,
|
final int refId,
|
||||||
final String modifiersString,
|
final ReadableArray listeners,
|
||||||
final String eventName,
|
|
||||||
final Callback callback) {
|
final Callback callback) {
|
||||||
|
|
||||||
String key = this.getDBListenerKey(path, modifiersString);
|
RNFirebaseDatabaseReference r = mReferences.get(refId);
|
||||||
RNFirebaseDatabaseReference r = mDBListeners.get(key);
|
|
||||||
|
|
||||||
if (r != null) {
|
if (r != null) {
|
||||||
if (eventName == null || "".equals(eventName)) {
|
List<Object> listenersList = Utils.recursivelyDeconstructReadableArray(listeners);
|
||||||
r.cleanup();
|
|
||||||
mDBListeners.remove(key);
|
for (Object l : listenersList) {
|
||||||
} else {
|
Map<String, Object> listener = (Map) l;
|
||||||
r.removeEventListener(eventName);
|
int listenerId = ((Double) listener.get("listenerId")).intValue();
|
||||||
|
String eventName = (String) listener.get("eventName");
|
||||||
|
r.removeEventListener(listenerId, eventName);
|
||||||
if (!r.hasListeners()) {
|
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();
|
WritableMap resp = Arguments.createMap();
|
||||||
resp.putString("handle", path);
|
resp.putInt("refId", refId);
|
||||||
resp.putString("status", "success");
|
resp.putString("status", "success");
|
||||||
resp.putString("modifiersString", modifiersString);
|
|
||||||
//TODO: Remaining listeners
|
|
||||||
callback.invoke(null, resp);
|
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) {
|
private RNFirebaseDatabaseReference getDBHandle(final int refId, final String path,
|
||||||
String key = this.getDBListenerKey(path, modifiersString);
|
final ReadableArray modifiers) {
|
||||||
RNFirebaseDatabaseReference r = mDBListeners.get(key);
|
RNFirebaseDatabaseReference r = mReferences.get(refId);
|
||||||
|
|
||||||
if (r == null) {
|
if (r == null) {
|
||||||
ReactContext ctx = getReactApplicationContext();
|
ReactContext ctx = getReactApplicationContext();
|
||||||
r = new RNFirebaseDatabaseReference(ctx, mFirebaseDatabase, path, modifiersArray, modifiersString);
|
r = new RNFirebaseDatabaseReference(ctx, mFirebaseDatabase, refId, path, modifiers);
|
||||||
mDBListeners.put(key, r);
|
mReferences.put(refId, r);
|
||||||
}
|
}
|
||||||
|
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
private String getDBListenerKey(String path, String modifiersString) {
|
|
||||||
return path + " | " + modifiersString;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, Object> getConstants() {
|
public Map<String, Object> getConstants() {
|
||||||
final Map<String, Object> constants = new HashMap<>();
|
final Map<String, Object> constants = new HashMap<>();
|
||||||
|
|
|
@ -1,9 +1,11 @@
|
||||||
package io.invertase.firebase.database;
|
package io.invertase.firebase.database;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
import com.facebook.react.bridge.Callback;
|
import com.facebook.react.bridge.Callback;
|
||||||
|
@ -25,81 +27,87 @@ public class RNFirebaseDatabaseReference {
|
||||||
private static final String TAG = "RNFirebaseDBReference";
|
private static final String TAG = "RNFirebaseDBReference";
|
||||||
|
|
||||||
private Query mQuery;
|
private Query mQuery;
|
||||||
|
private int mRefId;
|
||||||
private String mPath;
|
private String mPath;
|
||||||
private String mModifiersString;
|
private Map<Integer, ChildEventListener> mChildEventListeners = new HashMap<>();
|
||||||
private ChildEventListener mEventListener;
|
private Map<Integer, ValueEventListener> mValueEventListeners = new HashMap<>();
|
||||||
private ValueEventListener mValueListener;
|
|
||||||
private ReactContext mReactContext;
|
private ReactContext mReactContext;
|
||||||
private Set<String> childEventListeners = new HashSet<>();
|
|
||||||
|
|
||||||
public RNFirebaseDatabaseReference(final ReactContext context,
|
public RNFirebaseDatabaseReference(final ReactContext context,
|
||||||
final FirebaseDatabase firebaseDatabase,
|
final FirebaseDatabase firebaseDatabase,
|
||||||
|
final int refId,
|
||||||
final String path,
|
final String path,
|
||||||
final ReadableArray modifiersArray,
|
final ReadableArray modifiersArray) {
|
||||||
final String modifiersString) {
|
|
||||||
mReactContext = context;
|
mReactContext = context;
|
||||||
|
mRefId = refId;
|
||||||
mPath = path;
|
mPath = path;
|
||||||
mModifiersString = modifiersString;
|
|
||||||
mQuery = this.buildDatabaseQueryAtPathAndModifiers(firebaseDatabase, path, modifiersArray);
|
mQuery = this.buildDatabaseQueryAtPathAndModifiers(firebaseDatabase, path, modifiersArray);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addChildEventListener(final String eventName) {
|
public void addChildEventListener(final int listenerId, final String eventName) {
|
||||||
if (mEventListener == null) {
|
if (!mChildEventListeners.containsKey(listenerId)) {
|
||||||
mEventListener = new ChildEventListener() {
|
ChildEventListener childEventListener = new ChildEventListener() {
|
||||||
@Override
|
@Override
|
||||||
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
|
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
|
||||||
handleDatabaseEvent("child_added", dataSnapshot);
|
if ("child_added".equals(eventName)) {
|
||||||
|
handleDatabaseEvent("child_added", listenerId, dataSnapshot);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
|
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
|
||||||
handleDatabaseEvent("child_changed", dataSnapshot);
|
if ("child_changed".equals(eventName)) {
|
||||||
|
handleDatabaseEvent("child_changed", listenerId, dataSnapshot);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onChildRemoved(DataSnapshot dataSnapshot) {
|
public void onChildRemoved(DataSnapshot dataSnapshot) {
|
||||||
handleDatabaseEvent("child_removed", dataSnapshot);
|
if ("child_removed".equals(eventName)) {
|
||||||
|
handleDatabaseEvent("child_removed", listenerId, dataSnapshot);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
|
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
|
||||||
handleDatabaseEvent("child_moved", dataSnapshot);
|
if ("child_moved".equals(eventName)) {
|
||||||
|
handleDatabaseEvent("child_moved", listenerId, dataSnapshot);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onCancelled(DatabaseError error) {
|
public void onCancelled(DatabaseError error) {
|
||||||
removeChildEventListener();
|
removeChildEventListener(listenerId);
|
||||||
handleDatabaseError(error);
|
handleDatabaseError(listenerId, error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
mQuery.addChildEventListener(mEventListener);
|
mChildEventListeners.put(listenerId, childEventListener);
|
||||||
Log.d(TAG, "Added ChildEventListener for path: " + mPath + " with modifiers: "+ mModifiersString);
|
mQuery.addChildEventListener(childEventListener);
|
||||||
|
Log.d(TAG, "Added ChildEventListener for refId: " + mRefId + " listenerId: " + listenerId);
|
||||||
} else {
|
} 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() {
|
public void addValueEventListener(final int listenerId) {
|
||||||
if (mValueListener == null) {
|
if (!mValueEventListeners.containsKey(listenerId)) {
|
||||||
mValueListener = new ValueEventListener() {
|
ValueEventListener valueEventListener = new ValueEventListener() {
|
||||||
@Override
|
@Override
|
||||||
public void onDataChange(DataSnapshot dataSnapshot) {
|
public void onDataChange(DataSnapshot dataSnapshot) {
|
||||||
handleDatabaseEvent("value", dataSnapshot);
|
handleDatabaseEvent("value", listenerId, dataSnapshot);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onCancelled(DatabaseError error) {
|
public void onCancelled(DatabaseError error) {
|
||||||
removeValueEventListener();
|
removeValueEventListener(listenerId);
|
||||||
handleDatabaseError(error);
|
handleDatabaseError(listenerId, error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
mQuery.addValueEventListener(mValueListener);
|
mValueEventListeners.put(listenerId, valueEventListener);
|
||||||
Log.d(TAG, "Added ValueEventListener for path: " + mPath + " with modifiers: "+ mModifiersString);
|
mQuery.addValueEventListener(valueEventListener);
|
||||||
//this.setListeningTo(mPath, modifiersString, "value");
|
Log.d(TAG, "Added ValueEventListener for refId: " + mRefId + " listenerId: " + listenerId);
|
||||||
} else {
|
} 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() {
|
final ValueEventListener onceValueEventListener = new ValueEventListener() {
|
||||||
@Override
|
@Override
|
||||||
public void onDataChange(DataSnapshot dataSnapshot) {
|
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);
|
callback.invoke(null, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onCancelled(DatabaseError error) {
|
public void onCancelled(DatabaseError error) {
|
||||||
WritableMap err = Arguments.createMap();
|
WritableMap err = Arguments.createMap();
|
||||||
|
err.putInt("refId", mRefId);
|
||||||
err.putString("path", mPath);
|
err.putString("path", mPath);
|
||||||
err.putInt("code", error.getCode());
|
err.putInt("code", error.getCode());
|
||||||
err.putString("modifiers", mModifiersString);
|
|
||||||
err.putString("details", error.getDetails());
|
err.putString("details", error.getDetails());
|
||||||
err.putString("message", error.getMessage());
|
err.putString("message", error.getMessage());
|
||||||
callback.invoke(err);
|
callback.invoke(err);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
mQuery.addListenerForSingleValueEvent(onceValueEventListener);
|
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)) {
|
if ("value".equals(eventName)) {
|
||||||
this.removeValueEventListener();
|
this.removeValueEventListener(listenerId);
|
||||||
} else {
|
} else {
|
||||||
childEventListeners.remove(eventName);
|
this.removeChildEventListener(listenerId);
|
||||||
if (childEventListeners.isEmpty()) {
|
|
||||||
this.removeChildEventListener();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean hasListeners() {
|
public boolean hasListeners() {
|
||||||
return mEventListener != null || mValueListener != null;
|
return !mChildEventListeners.isEmpty() || !mValueEventListeners.isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void cleanup() {
|
public void cleanup() {
|
||||||
Log.d(TAG, "cleaning up database reference " + this);
|
Log.d(TAG, "cleaning up database reference " + this);
|
||||||
childEventListeners.clear();
|
this.removeChildEventListener(null);
|
||||||
this.removeChildEventListener();
|
this.removeValueEventListener(null);
|
||||||
this.removeValueEventListener();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void removeChildEventListener() {
|
private void removeChildEventListener(Integer listenerId) {
|
||||||
if (mEventListener != null) {
|
ChildEventListener listener = mChildEventListeners.remove(listenerId);
|
||||||
mQuery.removeEventListener(mEventListener);
|
if (listener != null) {
|
||||||
mEventListener = null;
|
mQuery.removeEventListener(listener);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void removeValueEventListener() {
|
private void removeValueEventListener(Integer listenerId) {
|
||||||
if (mValueListener != null) {
|
ValueEventListener listener = mValueEventListeners.remove(listenerId);
|
||||||
mQuery.removeEventListener(mValueListener);
|
if (listener != null) {
|
||||||
mValueListener = null;
|
mQuery.removeEventListener(listener);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleDatabaseEvent(final String name, final DataSnapshot dataSnapshot) {
|
private void handleDatabaseEvent(final String name, final Integer listenerId, final DataSnapshot dataSnapshot) {
|
||||||
WritableMap data = Utils.snapshotToMap(name, mPath, mModifiersString, dataSnapshot);
|
WritableMap data = Utils.snapshotToMap(name, mRefId, listenerId, mPath, dataSnapshot);
|
||||||
WritableMap evt = Arguments.createMap();
|
WritableMap evt = Arguments.createMap();
|
||||||
evt.putString("eventName", name);
|
evt.putString("eventName", name);
|
||||||
evt.putMap("body", data);
|
evt.putMap("body", data);
|
||||||
|
@ -171,12 +175,15 @@ public class RNFirebaseDatabaseReference {
|
||||||
Utils.sendEvent(mReactContext, "database_event", evt);
|
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();
|
WritableMap errMap = Arguments.createMap();
|
||||||
|
|
||||||
|
errMap.putInt("refId", mRefId);
|
||||||
|
if (listenerId != null) {
|
||||||
|
errMap.putInt("listenerId", listenerId);
|
||||||
|
}
|
||||||
errMap.putString("path", mPath);
|
errMap.putString("path", mPath);
|
||||||
errMap.putInt("code", error.getCode());
|
errMap.putInt("code", error.getCode());
|
||||||
errMap.putString("modifiers", mModifiersString);
|
|
||||||
errMap.putString("details", error.getDetails());
|
errMap.putString("details", error.getDetails());
|
||||||
errMap.putString("message", error.getMessage());
|
errMap.putString("message", error.getMessage());
|
||||||
|
|
||||||
|
@ -187,104 +194,102 @@ public class RNFirebaseDatabaseReference {
|
||||||
final String path,
|
final String path,
|
||||||
final ReadableArray modifiers) {
|
final ReadableArray modifiers) {
|
||||||
Query query = firebaseDatabase.getReference(path);
|
Query query = firebaseDatabase.getReference(path);
|
||||||
List<Object> strModifiers = Utils.recursivelyDeconstructReadableArray(modifiers);
|
List<Object> modifiersList = Utils.recursivelyDeconstructReadableArray(modifiers);
|
||||||
|
|
||||||
for (Object strModifier : strModifiers) {
|
for (Object m : modifiersList) {
|
||||||
String str = (String) strModifier;
|
Map<String, Object> modifier = (Map) m;
|
||||||
|
String type = (String) modifier.get("type");
|
||||||
|
String name = (String) modifier.get("name");
|
||||||
|
|
||||||
String[] strArr = str.split(":");
|
if ("orderBy".equals(type)) {
|
||||||
String methStr = strArr[0];
|
if ("orderByKey".equals(name)) {
|
||||||
|
|
||||||
if (methStr.equalsIgnoreCase("orderByKey")) {
|
|
||||||
query = query.orderByKey();
|
query = query.orderByKey();
|
||||||
} else if (methStr.equalsIgnoreCase("orderByValue")) {
|
} else if ("orderByPriority".equals(name)) {
|
||||||
query = query.orderByValue();
|
|
||||||
} else if (methStr.equalsIgnoreCase("orderByPriority")) {
|
|
||||||
query = query.orderByPriority();
|
query = query.orderByPriority();
|
||||||
} else if (methStr.contains("orderByChild")) {
|
} else if ("orderByValue".equals(name)) {
|
||||||
String key = strArr[1];
|
query = query.orderByValue();
|
||||||
Log.d(TAG, "orderByChild: " + key);
|
} else if ("orderByChild".equals(name)) {
|
||||||
|
String key = (String) modifier.get("key");
|
||||||
query = query.orderByChild(key);
|
query = query.orderByChild(key);
|
||||||
} else if (methStr.contains("limitToLast")) {
|
}
|
||||||
String key = strArr[1];
|
} else if ("limit".equals(type)) {
|
||||||
int limit = Integer.parseInt(key);
|
int limit = ((Double)modifier.get("limit")).intValue();
|
||||||
Log.d(TAG, "limitToLast: " + limit);
|
if ("limitToLast".equals(name)) {
|
||||||
query = query.limitToLast(limit);
|
query = query.limitToLast(limit);
|
||||||
} else if (methStr.contains("limitToFirst")) {
|
} else if ("limitToFirst".equals(name)) {
|
||||||
String key = strArr[1];
|
|
||||||
int limit = Integer.parseInt(key);
|
|
||||||
Log.d(TAG, "limitToFirst: " + limit);
|
|
||||||
query = query.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)) {
|
} else if ("filter".equals(type)) {
|
||||||
boolean booleanValue = Boolean.parseBoolean(value);
|
String valueType = (String) modifier.get("valueType");
|
||||||
if (strArr.length > 3) {
|
String key = (String) modifier.get("key");
|
||||||
query = query.equalTo(booleanValue, strArr[3]);
|
if ("equalTo".equals(name)) {
|
||||||
} else {
|
if ("number".equals(valueType)) {
|
||||||
query = query.equalTo(booleanValue);
|
double value = (Double) modifier.get("value");
|
||||||
}
|
if (key == null) {
|
||||||
} else {
|
|
||||||
if (strArr.length > 3) {
|
|
||||||
query = query.equalTo(value, strArr[3]);
|
|
||||||
} else {
|
|
||||||
query = query.equalTo(value);
|
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 (methStr.contains("endAt")) {
|
} else if ("endAt".equals(name)) {
|
||||||
String value = strArr[1];
|
if ("number".equals(valueType)) {
|
||||||
String type = strArr[2];
|
double value = (Double) modifier.get("value");
|
||||||
if ("number".equals(type)) {
|
if (key == null) {
|
||||||
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);
|
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 (methStr.contains("startAt")) {
|
} else if ("startAt".equals(name)) {
|
||||||
String value = strArr[1];
|
if ("number".equals(valueType)) {
|
||||||
String type = strArr[2];
|
double value = (Double) modifier.get("value");
|
||||||
if ("number".equals(type)) {
|
if (key == null) {
|
||||||
double doubleValue = Double.parseDouble(value);
|
|
||||||
if (strArr.length > 3) {
|
|
||||||
query = query.startAt(doubleValue, strArr[3]);
|
|
||||||
} else {
|
|
||||||
query = query.startAt(doubleValue);
|
|
||||||
}
|
|
||||||
} 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 (strArr.length > 3) {
|
|
||||||
query = query.startAt(value, strArr[3]);
|
|
||||||
} else {
|
|
||||||
query = query.startAt(value);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,25 @@
|
||||||
|
|
||||||
|
<h1 align="center">
|
||||||
|
<img src="https://camo.githubusercontent.com/6c827e5a0bb91259f82a1f4923ab7efa4891b119/687474703a2f2f692e696d6775722e636f6d2f303158514c30782e706e67"/><br>
|
||||||
|
|
||||||
|
React Native Firebase
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<div style="text-align: center;">
|
||||||
|
[![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)
|
||||||
|
<br />
|
||||||
|
A well tested Firebase implementation for React Native, supporting both iOS & Android apps.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
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!
|
|
@ -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)
|
|
@ -1 +0,0 @@
|
||||||
# Remote Config
|
|
|
@ -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());
|
|
||||||
});
|
|
||||||
```
|
|
|
@ -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.
|
|
@ -0,0 +1,3 @@
|
||||||
|
# Testing
|
||||||
|
|
||||||
|
|
12
docs/faqs.md
12
docs/faqs.md
|
@ -1,6 +1,6 @@
|
||||||
# FAQs / Troubleshooting
|
# 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.
|
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,
|
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
|
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.
|
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 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,
|
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.
|
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
|
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.
|
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:
|
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.
|
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:
|
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
|
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:
|
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... '
|
'Failed on android with com.android.dex.DexException: Multiple dex files... '
|
||||||
|
|
|
@ -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)
|
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.
|
Each platform uses a different setup method after creating the project.
|
||||||
|
|
||||||
## iOS
|
## 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
|
## Android
|
||||||
|
|
||||||
See the [android setup guide](./installation.android.md).
|
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)
|
||||||
## Usage
|
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).
|
||||||
|
|
||||||
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;
|
|
||||||
```
|
|
||||||
|
|
|
@ -0,0 +1,54 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>react-native-firebase - A react native firebase library supporting both android and ios native firebase SDK's</title>
|
||||||
|
<meta name="description" content="A react native firebase library supporting both android and ios native firebase SDK's">
|
||||||
|
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
|
||||||
|
<link rel="shortcut icon" type="image/png" href="https://camo.githubusercontent.com/6c827e5a0bb91259f82a1f4923ab7efa4891b119/687474703a2f2f692e696d6775722e636f6d2f303158514c30782e706e67"/>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
</body>
|
||||||
|
<script>
|
||||||
|
window.$docsify = {
|
||||||
|
name: 'react-native-firebase',
|
||||||
|
repo: 'https://github.com/invertase/react-native-firebase',
|
||||||
|
loadSidebar: true,
|
||||||
|
search: 'auto',
|
||||||
|
themeColor: '#f5820b',
|
||||||
|
subMaxLevel: 2,
|
||||||
|
maxLevel: 4,
|
||||||
|
ga: 'UA-98196653-1',
|
||||||
|
plugins: [
|
||||||
|
function (hook) {
|
||||||
|
var footer = [
|
||||||
|
'<hr/>',
|
||||||
|
'<footer>',
|
||||||
|
`<span>Caught a mistake or want to contribute to the documentation? <a href="https://github.com/invertase/react-native-firebase/tree/master/docs" target="_blank">Edit documentation on Github!</a>.</span>`,
|
||||||
|
'</footer>'
|
||||||
|
].join('');
|
||||||
|
|
||||||
|
hook.afterEach(function (html) {
|
||||||
|
return html + footer
|
||||||
|
})
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
<script>
|
||||||
|
if (typeof navigator.serviceWorker !== 'undefined') {
|
||||||
|
navigator.serviceWorker.register('sw.js')
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
<script src="//unpkg.com/docsify/lib/docsify.min.js"></script>
|
||||||
|
<script src="//unpkg.com/docsify/lib/plugins/search.js"></script>
|
||||||
|
<link rel="stylesheet" href="//unpkg.com/docsify/themes/vue.css">
|
||||||
|
<script src="//unpkg.com/docsify/lib/plugins/emoji.min.js"></script>
|
||||||
|
<script src="//unpkg.com/docsify/lib/plugins/ga.min.js"></script>
|
||||||
|
<script src="//unpkg.com/prismjs/components/prism-bash.min.js"></script>
|
||||||
|
<script src="//unpkg.com/prismjs/components/prism-javascript.min.js"></script>
|
||||||
|
<script src="//unpkg.com/prismjs/components/prism-java.min.js"></script>
|
||||||
|
<script src="//unpkg.com/prismjs/components/prism-swift.min.js"></script>
|
||||||
|
<script src="//unpkg.com/prismjs/components/prism-objectivec.min.js"></script>
|
||||||
|
</html>
|
|
@ -1,6 +1,6 @@
|
||||||
# Android Installation
|
# 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`.
|
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.
|
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'
|
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:
|
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')
|
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`.
|
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`.
|
||||||
|
|
|
@ -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).
|
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:
|
Make sure you've added the following to the top of your `ios/[YOUR APP NAME]]/AppDelegate.m` file:
|
||||||
|
|
||||||
`#import <Firebase.h>`
|
`#import <Firebase.h>`
|
||||||
|
@ -12,10 +12,11 @@ and this to the `didFinishLaunchingWithOptions:(NSDictionary *)launchOptions` me
|
||||||
|
|
||||||
`[FIRApp configure];`
|
`[FIRApp configure];`
|
||||||
|
|
||||||
### 2 - Link RNFirebase
|
## 2) Link RNFirebase
|
||||||
|
|
||||||
There are multiple ways to install RNFirebase depending on how your project is currently setup:
|
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`:
|
Simply add the following to your `Podfile`:
|
||||||
|
|
||||||
```ruby
|
```ruby
|
||||||
|
@ -33,25 +34,27 @@ pod 'Firebase/Storage'
|
||||||
pod 'RNFirebase', :path => '../node_modules/react-native-firebase'
|
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.
|
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
|
```bash
|
||||||
react-native link react-native-firebase
|
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:
|
Update the newly installed pods once the linking is done:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd ios && pod update --verbose
|
cd ios && pod update --verbose
|
||||||
```
|
```
|
||||||
|
|
||||||
##### cocoapods
|
**NOTE: You need to use the `ios/[YOUR APP NAME].xcworkspace` instead of the `ios/[YOUR APP NAME].xcproj` file from now on.**
|
||||||
We've automated the process of setting up with cocoapods. This will happen automatically upon linking the package with `react-native-cli`.
|
|
||||||
|
|
||||||
**Remember to use the `ios/[YOUR APP NAME].xcworkspace` instead of the `ios/[YOUR APP NAME].xcproj` file from now on**.
|
### 2.3) You're not using Cocoapods or don't have React Native installed as a pod (Manual install)
|
||||||
|
|
||||||
#### 2.3 - Manually
|
|
||||||
|
|
||||||
If you prefer not to use `react-native link`, we can manually link the package together with the following steps, after `npm 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'
|
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 <UIApplicationDelegate,UNUserNotificationCenterDelegate>`
|
||||||
|
|
||||||
|
### 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];
|
||||||
|
}
|
||||||
|
```
|
|
@ -72,7 +72,7 @@ class MyComponent extends Component {
|
||||||
|
|
||||||
### Reading data
|
### 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:
|
To enable database persistence, pass the configuration option `persistence` before calls are made:
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
|
@ -181,7 +181,7 @@ class ToDos extends Component {
|
||||||
#### Differences between `.on` & `.once`
|
#### 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.
|
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.
|
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.
|
The database refs has a `keepSynced()` function to tell the RNFirebase library to keep the data at the `ref` in sync.
|
|
@ -3,8 +3,6 @@
|
||||||
RNFirebase mimics the [Web Firebase SDK Storage](https://firebase.google.com/docs/storage/web/start), whilst
|
RNFirebase mimics the [Web Firebase SDK Storage](https://firebase.google.com/docs/storage/web/start), whilst
|
||||||
providing some iOS and Android specific functionality.
|
providing some iOS and Android specific functionality.
|
||||||
|
|
||||||
All Storage operations are accessed via `storage()`.
|
|
||||||
|
|
||||||
## Uploading files
|
## Uploading files
|
||||||
|
|
||||||
### Simple
|
### Simple
|
|
@ -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());
|
||||||
|
});
|
||||||
|
```
|
|
@ -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<Response> 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 */ })
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
|
@ -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;
|
||||||
|
```
|
71
ios/Podfile
71
ios/Podfile
|
@ -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
|
|
|
@ -8,3 +8,4 @@ pod 'Firebase/DynamicLinks'
|
||||||
pod 'Firebase/Messaging'
|
pod 'Firebase/Messaging'
|
||||||
pod 'Firebase/RemoteConfig'
|
pod 'Firebase/RemoteConfig'
|
||||||
pod 'Firebase/Storage'
|
pod 'Firebase/Storage'
|
||||||
|
pod 'RNFirebase', :path => '../node_modules/react-native-firebase'
|
||||||
|
|
|
@ -5,64 +5,61 @@
|
||||||
@interface RNFirebaseDBReference : NSObject
|
@interface RNFirebaseDBReference : NSObject
|
||||||
@property RCTEventEmitter *emitter;
|
@property RCTEventEmitter *emitter;
|
||||||
@property FIRDatabaseQuery *query;
|
@property FIRDatabaseQuery *query;
|
||||||
|
@property NSNumber *refId;
|
||||||
@property NSString *path;
|
@property NSString *path;
|
||||||
@property NSString *modifiersString;
|
|
||||||
@property NSMutableDictionary *listeners;
|
@property NSMutableDictionary *listeners;
|
||||||
@property FIRDatabaseHandle childAddedHandler;
|
|
||||||
@property FIRDatabaseHandle childModifiedHandler;
|
|
||||||
@property FIRDatabaseHandle childRemovedHandler;
|
|
||||||
@property FIRDatabaseHandle childMovedHandler;
|
|
||||||
@property FIRDatabaseHandle childValueHandler;
|
|
||||||
+ (NSDictionary *) snapshotToDict:(FIRDataSnapshot *) snapshot;
|
+ (NSDictionary *) snapshotToDict:(FIRDataSnapshot *) snapshot;
|
||||||
@end
|
@end
|
||||||
|
|
||||||
@implementation RNFirebaseDBReference
|
@implementation RNFirebaseDBReference
|
||||||
|
|
||||||
|
|
||||||
- (id) initWithPathAndModifiers:(RCTEventEmitter *) emitter
|
- (id) initWithPathAndModifiers:(RCTEventEmitter *) emitter
|
||||||
database:(FIRDatabase *) database
|
database:(FIRDatabase *) database
|
||||||
|
refId:(NSNumber *) refId
|
||||||
path:(NSString *) path
|
path:(NSString *) path
|
||||||
modifiers:(NSArray *) modifiers
|
modifiers:(NSArray *) modifiers
|
||||||
modifiersString:(NSString *) modifiersString
|
|
||||||
{
|
{
|
||||||
self = [super init];
|
self = [super init];
|
||||||
if (self) {
|
if (self) {
|
||||||
_emitter = emitter;
|
_emitter = emitter;
|
||||||
|
_refId = refId;
|
||||||
_path = path;
|
_path = path;
|
||||||
_modifiersString = modifiersString;
|
|
||||||
_query = [self buildQueryAtPathWithModifiers:database path:path modifiers:modifiers];
|
_query = [self buildQueryAtPathWithModifiers:database path:path modifiers:modifiers];
|
||||||
_listeners = [[NSMutableDictionary alloc] init];
|
_listeners = [[NSMutableDictionary alloc] init];
|
||||||
}
|
}
|
||||||
return self;
|
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) {
|
id withBlock = ^(FIRDataSnapshot * _Nonnull snapshot) {
|
||||||
NSDictionary *props = [RNFirebaseDBReference snapshotToDict:snapshot];
|
NSDictionary *props = [RNFirebaseDBReference snapshotToDict:snapshot];
|
||||||
[self sendJSEvent:DATABASE_DATA_EVENT
|
[self sendJSEvent:DATABASE_DATA_EVENT
|
||||||
title:eventName
|
title:eventName
|
||||||
props: @{
|
props: @{
|
||||||
@"eventName": eventName,
|
@"eventName": eventName,
|
||||||
|
@"refId": _refId,
|
||||||
|
@"listenerId": listenerId,
|
||||||
@"path": _path,
|
@"path": _path,
|
||||||
@"modifiersString": _modifiersString,
|
|
||||||
@"snapshot": props
|
@"snapshot": props
|
||||||
}];
|
}];
|
||||||
};
|
};
|
||||||
id errorBlock = ^(NSError * _Nonnull error) {
|
id errorBlock = ^(NSError * _Nonnull error) {
|
||||||
NSLog(@"Error onDBEvent: %@", [error debugDescription]);
|
NSLog(@"Error onDBEvent: %@", [error debugDescription]);
|
||||||
[self unsetListeningOn:eventName];
|
[self removeEventHandler:listenerId eventName:eventName];
|
||||||
[self getAndSendDatabaseError:error
|
[self getAndSendDatabaseError:error
|
||||||
path:_path
|
listenerId:listenerId];
|
||||||
modifiersString:_modifiersString];
|
|
||||||
};
|
};
|
||||||
int eventType = [self eventTypeFromName:eventName];
|
int eventType = [self eventTypeFromName:eventName];
|
||||||
FIRDatabaseHandle handle = [_query observeEventType:eventType
|
FIRDatabaseHandle handle = [_query observeEventType:eventType
|
||||||
withBlock:withBlock
|
withBlock:withBlock
|
||||||
withCancelBlock:errorBlock];
|
withCancelBlock:errorBlock];
|
||||||
[self setEventHandler:handle forName:eventName];
|
[_listeners setObject:@(handle) forKey:listenerId];
|
||||||
} else {
|
} 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], @{
|
callback(@[[NSNull null], @{
|
||||||
@"eventName": @"value",
|
@"eventName": @"value",
|
||||||
@"path": _path,
|
@"path": _path,
|
||||||
@"modifiersString": _modifiersString,
|
@"refId": _refId,
|
||||||
@"snapshot": props
|
@"snapshot": props
|
||||||
}]);
|
}]);
|
||||||
}
|
}
|
||||||
|
@ -83,7 +80,7 @@
|
||||||
callback(@[@{
|
callback(@[@{
|
||||||
@"eventName": DATABASE_ERROR_EVENT,
|
@"eventName": DATABASE_ERROR_EVENT,
|
||||||
@"path": _path,
|
@"path": _path,
|
||||||
@"modifiers": _modifiersString,
|
@"refId": _refId,
|
||||||
@"code": @([error code]),
|
@"code": @([error code]),
|
||||||
@"details": [error debugDescription],
|
@"details": [error debugDescription],
|
||||||
@"message": [error localizedDescription],
|
@"message": [error localizedDescription],
|
||||||
|
@ -92,44 +89,14 @@
|
||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void) removeEventHandler:(NSString *) name
|
- (void) removeEventHandler:(NSNumber *) listenerId
|
||||||
|
eventName:(NSString *) eventName
|
||||||
{
|
{
|
||||||
int eventType = [self eventTypeFromName:name];
|
FIRDatabaseHandle handle = [[_listeners objectForKey:listenerId] integerValue];
|
||||||
switch (eventType) {
|
if (handle) {
|
||||||
case FIRDataEventTypeValue:
|
[_listeners removeObjectForKey:listenerId];
|
||||||
if (self.childValueHandler != nil) {
|
[_query removeObserverWithHandle:handle];
|
||||||
[_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;
|
|
||||||
}
|
|
||||||
[self unsetListeningOn:name];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
+ (NSDictionary *) snapshotToDict:(FIRDataSnapshot *) snapshot
|
+ (NSDictionary *) snapshotToDict:(FIRDataSnapshot *) snapshot
|
||||||
|
@ -159,21 +126,19 @@
|
||||||
}
|
}
|
||||||
|
|
||||||
- (NSDictionary *) getAndSendDatabaseError:(NSError *) error
|
- (NSDictionary *) getAndSendDatabaseError:(NSError *) error
|
||||||
path:(NSString *) path
|
listenerId:(NSNumber *) listenerId
|
||||||
modifiersString:(NSString *) modifiersString
|
|
||||||
{
|
{
|
||||||
NSDictionary *event = @{
|
NSDictionary *event = @{
|
||||||
@"eventName": DATABASE_ERROR_EVENT,
|
@"eventName": DATABASE_ERROR_EVENT,
|
||||||
@"path": path,
|
@"path": _path,
|
||||||
@"modifiers": modifiersString,
|
@"refId": _refId,
|
||||||
|
@"listenerId": listenerId,
|
||||||
@"code": @([error code]),
|
@"code": @([error code]),
|
||||||
@"details": [error debugDescription],
|
@"details": [error debugDescription],
|
||||||
@"message": [error localizedDescription],
|
@"message": [error localizedDescription],
|
||||||
@"description": [error description]
|
@"description": [error description]
|
||||||
};
|
};
|
||||||
|
|
||||||
// [self sendJSEvent:DATABASE_ERROR_EVENT title:DATABASE_ERROR_EVENT props: event];
|
|
||||||
|
|
||||||
@try {
|
@try {
|
||||||
[_emitter sendEventWithName:DATABASE_ERROR_EVENT body:event];
|
[_emitter sendEventWithName:DATABASE_ERROR_EVENT body:event];
|
||||||
}
|
}
|
||||||
|
@ -194,69 +159,58 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
- (FIRDatabaseQuery *) buildQueryAtPathWithModifiers:(FIRDatabase*) database
|
- (FIRDatabaseQuery *) buildQueryAtPathWithModifiers:(FIRDatabase*) database
|
||||||
path:(NSString*) path
|
path:(NSString*) path
|
||||||
modifiers:(NSArray *) modifiers
|
modifiers:(NSArray *) modifiers
|
||||||
{
|
{
|
||||||
FIRDatabaseQuery *query = [[database reference] child:path];
|
FIRDatabaseQuery *query = [[database reference] child:path];
|
||||||
|
|
||||||
for (NSString *str in modifiers) {
|
for (NSDictionary *modifier in modifiers) {
|
||||||
if ([str isEqualToString:@"orderByKey"]) {
|
NSString *type = [modifier valueForKey:@"type"];
|
||||||
|
NSString *name = [modifier valueForKey:@"name"];
|
||||||
|
if ([type isEqualToString:@"orderBy"]) {
|
||||||
|
if ([name isEqualToString:@"orderByKey"]) {
|
||||||
query = [query queryOrderedByKey];
|
query = [query queryOrderedByKey];
|
||||||
} else if ([str isEqualToString:@"orderByPriority"]) {
|
} else if ([name isEqualToString:@"orderByPriority"]) {
|
||||||
query = [query queryOrderedByPriority];
|
query = [query queryOrderedByPriority];
|
||||||
} else if ([str isEqualToString:@"orderByValue"]) {
|
} else if ([name isEqualToString:@"orderByValue"]) {
|
||||||
query = [query queryOrderedByValue];
|
query = [query queryOrderedByValue];
|
||||||
} else if ([str containsString:@"orderByChild"]) {
|
} else if ([name isEqualToString:@"orderByChild"]) {
|
||||||
NSArray *args = [str componentsSeparatedByString:@":"];
|
NSString *key = [modifier valueForKey:@"key"];
|
||||||
NSString *key = args[1];
|
|
||||||
query = [query queryOrderedByChild:key];
|
query = [query queryOrderedByChild:key];
|
||||||
} else if ([str containsString:@"limitToLast"]) {
|
}
|
||||||
NSArray *args = [str componentsSeparatedByString:@":"];
|
} else if ([type isEqualToString:@"limit"]) {
|
||||||
NSString *key = args[1];
|
int limit = [[modifier valueForKey:@"limit"] integerValue];
|
||||||
NSUInteger limit = key.integerValue;
|
if ([name isEqualToString:@"limitToLast"]) {
|
||||||
query = [query queryLimitedToLast:limit];
|
query = [query queryLimitedToLast:limit];
|
||||||
} else if ([str containsString:@"limitToFirst"]) {
|
} else if ([name isEqualToString:@"limitToFirst"]) {
|
||||||
NSArray *args = [str componentsSeparatedByString:@":"];
|
|
||||||
NSString *key = args[1];
|
|
||||||
NSUInteger limit = key.integerValue;
|
|
||||||
query = [query queryLimitedToFirst:limit];
|
query = [query queryLimitedToFirst:limit];
|
||||||
} else if ([str containsString:@"equalTo"]) {
|
}
|
||||||
NSArray *args = [str componentsSeparatedByString:@":"];
|
} else if ([type isEqualToString:@"filter"]) {
|
||||||
int size = (int)[args count];;
|
NSString* valueType = [modifier valueForKey:@"valueType"];
|
||||||
id value = [self getIdValue:args[1] type:args[2]];
|
NSString* key = [modifier valueForKey:@"key"];
|
||||||
if (size > 3) {
|
id value = [self getIdValue:[modifier valueForKey:@"value"] type:valueType];
|
||||||
NSString *key = args[3];
|
if ([name isEqualToString:@"equalTo"]) {
|
||||||
query = [query queryEqualToValue:value
|
if (key != nil) {
|
||||||
childKey:key];
|
query = [query queryEqualToValue:value childKey:key];
|
||||||
} else {
|
} else {
|
||||||
query = [query queryEqualToValue:value];
|
query = [query queryEqualToValue:value];
|
||||||
}
|
}
|
||||||
} else if ([str containsString:@"endAt"]) {
|
} else if ([name isEqualToString:@"endAt"]) {
|
||||||
NSArray *args = [str componentsSeparatedByString:@":"];
|
if (key != nil) {
|
||||||
int size = (int)[args count];;
|
query = [query queryEndingAtValue:value childKey:key];
|
||||||
id value = [self getIdValue:args[1] type:args[2]];
|
|
||||||
if (size > 3) {
|
|
||||||
NSString *key = args[3];
|
|
||||||
query = [query queryEndingAtValue:value
|
|
||||||
childKey:key];
|
|
||||||
} else {
|
} else {
|
||||||
query = [query queryEndingAtValue:value];
|
query = [query queryEndingAtValue:value];
|
||||||
}
|
}
|
||||||
} else if ([str containsString:@"startAt"]) {
|
} else if ([name isEqualToString:@"startAt"]) {
|
||||||
NSArray *args = [str componentsSeparatedByString:@":"];
|
if (key != nil) {
|
||||||
id value = [self getIdValue:args[1] type:args[2]];
|
query = [query queryStartingAtValue:value childKey:key];
|
||||||
int size = (int)[args count];;
|
|
||||||
if (size > 3) {
|
|
||||||
NSString *key = args[3];
|
|
||||||
query = [query queryStartingAtValue:value
|
|
||||||
childKey:key];
|
|
||||||
} else {
|
} else {
|
||||||
query = [query queryStartingAtValue:value];
|
query = [query queryStartingAtValue:value];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
|
@ -273,58 +227,11 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
- (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
|
- (BOOL) hasListeners
|
||||||
{
|
{
|
||||||
return [[_listeners allKeys] count] > 0;
|
return [[_listeners allKeys] count] > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (NSArray *) listenerKeys
|
|
||||||
{
|
|
||||||
return [_listeners allKeys];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (int) eventTypeFromName:(NSString *)name
|
- (int) eventTypeFromName:(NSString *)name
|
||||||
{
|
{
|
||||||
int eventType = FIRDataEventTypeValue;
|
int eventType = FIRDataEventTypeValue;
|
||||||
|
@ -343,24 +250,6 @@
|
||||||
return eventType;
|
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
|
@end
|
||||||
|
|
||||||
|
|
||||||
|
@ -558,58 +447,50 @@ RCT_EXPORT_METHOD(push:(NSString *) path
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
RCT_EXPORT_METHOD(on:(nonnull NSNumber *) refId
|
||||||
RCT_EXPORT_METHOD(on:(NSString *) path
|
path:(NSString *) path
|
||||||
modifiersString:(NSString *) modifiersString
|
|
||||||
modifiers:(NSArray *) modifiers
|
modifiers:(NSArray *) modifiers
|
||||||
|
listenerId:(nonnull NSNumber *) listenerId
|
||||||
name:(NSString *) eventName
|
name:(NSString *) eventName
|
||||||
callback:(RCTResponseSenderBlock) callback)
|
callback:(RCTResponseSenderBlock) callback)
|
||||||
{
|
{
|
||||||
RNFirebaseDBReference *ref = [self getDBHandle:path modifiers:modifiers modifiersString:modifiersString];
|
RNFirebaseDBReference *ref = [self getDBHandle:refId path:path modifiers:modifiers];
|
||||||
[ref addEventHandler:eventName];
|
[ref addEventHandler:listenerId eventName:eventName];
|
||||||
callback(@[[NSNull null], @{
|
callback(@[[NSNull null], @{
|
||||||
@"status": @"success",
|
@"status": @"success",
|
||||||
|
@"refId": refId,
|
||||||
@"handle": path
|
@"handle": path
|
||||||
}]);
|
}]);
|
||||||
}
|
}
|
||||||
|
|
||||||
RCT_EXPORT_METHOD(once:(NSString *) path
|
RCT_EXPORT_METHOD(once:(nonnull NSNumber *) refId
|
||||||
modifiersString:(NSString *) modifiersString
|
path:(NSString *) path
|
||||||
modifiers:(NSArray *) modifiers
|
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
|
eventName:(NSString *) eventName
|
||||||
callback:(RCTResponseSenderBlock) callback)
|
callback:(RCTResponseSenderBlock) callback)
|
||||||
{
|
{
|
||||||
NSString *key = [self getDBListenerKey:path withModifiers:modifiersString];
|
RNFirebaseDBReference *ref = [self getDBHandle:refId path:path modifiers:modifiers];
|
||||||
NSArray *listenerKeys;
|
[ref addSingleEventHandler:callback];
|
||||||
RNFirebaseDBReference *ref = [_dbReferences objectForKey:key];
|
}
|
||||||
if (ref == nil) {
|
|
||||||
listenerKeys = @[];
|
RCT_EXPORT_METHOD(off:(nonnull NSNumber *) refId
|
||||||
} else {
|
listeners:(NSArray *) listeners
|
||||||
if (eventName == nil || [eventName isEqualToString:@""]) {
|
callback:(RCTResponseSenderBlock) callback)
|
||||||
[ref cleanup];
|
{
|
||||||
[_dbReferences removeObjectForKey:key];
|
RNFirebaseDBReference *ref = [_dbReferences objectForKey:refId];
|
||||||
} else {
|
if (ref != nil) {
|
||||||
[ref removeEventHandler:eventName];
|
for (NSDictionary *listener in listeners) {
|
||||||
|
NSNumber *listenerId = [listener valueForKey:@"listenerId"];
|
||||||
|
NSString *eventName = [listener valueForKey:@"eventName"];
|
||||||
|
[ref removeEventHandler:listenerId eventName:eventName];
|
||||||
if (![ref hasListeners]) {
|
if (![ref hasListeners]) {
|
||||||
[_dbReferences removeObjectForKey:key];
|
[_dbReferences removeObjectForKey:refId];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
listenerKeys = [ref listenerKeys];
|
|
||||||
}
|
}
|
||||||
callback(@[[NSNull null], @{
|
callback(@[[NSNull null], @{
|
||||||
@"result": @"success",
|
@"status": @"success",
|
||||||
@"handle": path,
|
@"refId": refId,
|
||||||
@"modifiersString": modifiersString,
|
|
||||||
@"remainingListeners": listenerKeys,
|
|
||||||
}]);
|
}]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -680,30 +561,23 @@ RCT_EXPORT_METHOD(goOnline)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
- (RNFirebaseDBReference *) getDBHandle:(NSString *) path
|
- (RNFirebaseDBReference *) getDBHandle:(NSNumber *) refId
|
||||||
modifiers:modifiers
|
path:(NSString *) path
|
||||||
modifiersString:modifiersString
|
modifiers:(NSArray *) modifiers
|
||||||
{
|
{
|
||||||
NSString *key = [self getDBListenerKey:path withModifiers:modifiersString];
|
RNFirebaseDBReference *ref = [_dbReferences objectForKey:refId];
|
||||||
RNFirebaseDBReference *ref = [_dbReferences objectForKey:key];
|
|
||||||
|
|
||||||
if (ref == nil) {
|
if (ref == nil) {
|
||||||
ref = [[RNFirebaseDBReference alloc] initWithPathAndModifiers:self
|
ref = [[RNFirebaseDBReference alloc] initWithPathAndModifiers:self
|
||||||
database:[FIRDatabase database]
|
database:[FIRDatabase database]
|
||||||
|
refId:refId
|
||||||
path:path
|
path:path
|
||||||
modifiers:modifiers
|
modifiers:modifiers];
|
||||||
modifiersString:modifiersString];
|
[_dbReferences setObject:ref forKey:refId];
|
||||||
[_dbReferences setObject:ref forKey:key];
|
|
||||||
}
|
}
|
||||||
return ref;
|
return ref;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (NSString *) getDBListenerKey:(NSString *) path
|
|
||||||
withModifiers:(NSString *) modifiersString
|
|
||||||
{
|
|
||||||
return [NSString stringWithFormat:@"%@ | %@", path, modifiersString, nil];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Not sure how to get away from this... yet
|
// Not sure how to get away from this... yet
|
||||||
- (NSArray<NSString *> *)supportedEvents {
|
- (NSArray<NSString *> *)supportedEvents {
|
||||||
return @[DATABASE_DATA_EVENT, DATABASE_ERROR_EVENT, DATABASE_TRANSACTION_EVENT];
|
return @[DATABASE_DATA_EVENT, DATABASE_ERROR_EVENT, DATABASE_TRANSACTION_EVENT];
|
||||||
|
|
|
@ -35,8 +35,10 @@ export default class Firebase {
|
||||||
_crash: ?Object;
|
_crash: ?Object;
|
||||||
|
|
||||||
auth: Function;
|
auth: Function;
|
||||||
|
crash: Function;
|
||||||
storage: Function;
|
storage: Function;
|
||||||
database: Function;
|
database: Function;
|
||||||
|
analytics: Function;
|
||||||
messaging: Function;
|
messaging: Function;
|
||||||
|
|
||||||
eventHandlers: Object;
|
eventHandlers: Object;
|
||||||
|
@ -79,6 +81,8 @@ export default class Firebase {
|
||||||
this.storage = this._staticsOrInstance('storage', StorageStatics, Storage);
|
this.storage = this._staticsOrInstance('storage', StorageStatics, Storage);
|
||||||
this.database = this._staticsOrInstance('database', DatabaseStatics, Database);
|
this.database = this._staticsOrInstance('database', DatabaseStatics, Database);
|
||||||
this.messaging = this._staticsOrInstance('messaging', MessagingStatics, Messaging);
|
this.messaging = this._staticsOrInstance('messaging', MessagingStatics, Messaging);
|
||||||
|
this.analytics = this._staticsOrInstance('analytics', {}, Analytics);
|
||||||
|
this.crash = this._staticsOrInstance('crash', {}, Crash);
|
||||||
|
|
||||||
// init auth to start listeners
|
// init auth to start listeners
|
||||||
this.auth();
|
this.auth();
|
||||||
|
@ -107,20 +111,6 @@ export default class Firebase {
|
||||||
return instances[name];
|
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<string> {
|
get apps(): Array<string> {
|
||||||
return Object.keys(instances);
|
return Object.keys(instances);
|
||||||
}
|
}
|
||||||
|
|
16
lib/flow.js
16
lib/flow.js
|
@ -15,6 +15,22 @@ declare type CredentialType = {
|
||||||
secret: string
|
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 = {
|
declare type GoogleApiAvailabilityType = {
|
||||||
status: number,
|
status: number,
|
||||||
isAvailable: boolean,
|
isAvailable: boolean,
|
||||||
|
|
|
@ -19,9 +19,8 @@ const FirebaseDatabaseEvt = new NativeEventEmitter(FirebaseDatabase);
|
||||||
export default class Database extends Base {
|
export default class Database extends Base {
|
||||||
constructor(firebase: Object, options: Object = {}) {
|
constructor(firebase: Object, options: Object = {}) {
|
||||||
super(firebase, options);
|
super(firebase, options);
|
||||||
this.subscriptions = {};
|
this.references = {};
|
||||||
this.serverTimeOffset = 0;
|
this.serverTimeOffset = 0;
|
||||||
this.errorSubscriptions = {};
|
|
||||||
this.persistenceEnabled = false;
|
this.persistenceEnabled = false;
|
||||||
this.namespace = 'firebase:database';
|
this.namespace = 'firebase:database';
|
||||||
this.transaction = new TransactionHandler(firebase, this, FirebaseDatabaseEvt);
|
this.transaction = new TransactionHandler(firebase, this, FirebaseDatabaseEvt);
|
||||||
|
@ -68,20 +67,12 @@ export default class Database extends Base {
|
||||||
* @param errorCb
|
* @param errorCb
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
on(path: string, modifiersString: string, modifiers: Array<string>, eventName: string, cb: () => void, errorCb: () => void) {
|
on(ref: Reference, listener: DatabaseListener) {
|
||||||
const handle = this._handle(path, modifiersString);
|
const { refId, path, query } = ref;
|
||||||
this.log.debug('adding on listener', handle);
|
const { listenerId, eventName } = listener;
|
||||||
|
this.log.debug('on() : ', ref.refId, listenerId, eventName);
|
||||||
if (!this.subscriptions[handle]) this.subscriptions[handle] = {};
|
this.references[refId] = ref;
|
||||||
if (!this.subscriptions[handle][eventName]) this.subscriptions[handle][eventName] = [];
|
return promisify('on', FirebaseDatabase)(refId, path, query.getModifiers(), listenerId, 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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -92,49 +83,35 @@ export default class Database extends Base {
|
||||||
* @param origCB
|
* @param origCB
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
off(path: string, modifiersString: string, eventName?: string, origCB?: () => void) {
|
off(
|
||||||
const handle = this._handle(path, modifiersString);
|
refId: number,
|
||||||
this.log.debug('off() : ', handle, eventName);
|
// $FlowFixMe
|
||||||
|
listeners: Array<DatabaseListener>,
|
||||||
|
remainingListenersCount: number
|
||||||
|
) {
|
||||||
|
this.log.debug('off() : ', refId, listeners);
|
||||||
|
|
||||||
if (!this.subscriptions[handle] || (eventName && !this.subscriptions[handle][eventName])) {
|
// Delete the reference if there are no more listeners
|
||||||
this.log.warn('off() called, but not currently listening at that location (bad path)', handle, eventName);
|
if (remainingListenersCount === 0) delete this.references[refId];
|
||||||
return Promise.resolve();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (eventName && origCB) {
|
if (listeners.length === 0) return Promise.resolve();
|
||||||
const i = this.subscriptions[handle][eventName].indexOf(origCB);
|
|
||||||
|
|
||||||
if (i === -1) {
|
return promisify('off', FirebaseDatabase)(refId, listeners.map(listener => ({
|
||||||
this.log.warn('off() called, but the callback specified is not listening at that location (bad path)', handle, eventName);
|
listenerId: listener.listenerId,
|
||||||
return Promise.resolve();
|
eventName: listener.eventName,
|
||||||
}
|
})));
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Removes all event handlers and their native subscriptions
|
* Removes all references and their native listeners
|
||||||
* @returns {Promise.<*>}
|
* @returns {Promise.<*>}
|
||||||
*/
|
*/
|
||||||
cleanup() {
|
cleanup() {
|
||||||
const promises = [];
|
const promises = [];
|
||||||
Object.keys(this.subscriptions).forEach((handle) => {
|
Object.keys(this.references).forEach((refId) => {
|
||||||
Object.keys(this.subscriptions[handle]).forEach((eventName) => {
|
const ref = this.references[refId];
|
||||||
const separator = handle.indexOf('|');
|
promises.push(this.off(Number(refId), Object.values(ref.listeners), 0));
|
||||||
const path = handle.substring(0, separator);
|
|
||||||
const modifiersString = handle.substring(separator + 1);
|
|
||||||
promises.push(this.off(path, modifiersString, eventName));
|
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
||||||
return Promise.all(promises);
|
return Promise.all(promises);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -169,18 +146,6 @@ export default class Database extends Base {
|
||||||
return Promise.reject({ status: 'Already enabled' });
|
return Promise.reject({ status: 'Already enabled' });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* @param path
|
|
||||||
* @param modifiersString
|
|
||||||
* @returns {string}
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
_handle(path: string = '', modifiersString: string = '') {
|
|
||||||
return `${path}|${modifiersString}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param event
|
* @param event
|
||||||
|
@ -188,18 +153,14 @@ export default class Database extends Base {
|
||||||
*/
|
*/
|
||||||
_handleDatabaseEvent(event: Object) {
|
_handleDatabaseEvent(event: Object) {
|
||||||
const body = event.body || {};
|
const body = event.body || {};
|
||||||
const { path, modifiersString, eventName, snapshot } = body;
|
const { refId, listenerId, path, eventName, snapshot } = body;
|
||||||
const handle = this._handle(path, modifiersString);
|
this.log.debug('_handleDatabaseEvent: ', refId, listenerId, path, eventName, snapshot && snapshot.key);
|
||||||
|
if (this.references[refId] && this.references[refId].listeners[listenerId]) {
|
||||||
this.log.debug('_handleDatabaseEvent: ', handle, eventName, snapshot && snapshot.key);
|
const cb = this.references[refId].listeners[listenerId].successCallback;
|
||||||
|
cb(new Snapshot(this.references[refId], snapshot));
|
||||||
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);
|
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
FirebaseDatabase.off(path, modifiersString, eventName, () => {
|
FirebaseDatabase.off(refId, [{ listenerId, eventName }], () => {
|
||||||
this.log.debug('_handleDatabaseEvent: No JS listener registered, removed native listener', handle, 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
|
* @private
|
||||||
*/
|
*/
|
||||||
_handleDatabaseError(error: Object = {}) {
|
_handleDatabaseError(error: Object = {}) {
|
||||||
const { path, modifiers } = error;
|
const { refId, listenerId, path } = error;
|
||||||
const handle = this._handle(path, modifiers);
|
|
||||||
const firebaseError = this._toFirebaseError(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' },
|
TIMESTAMP: FirebaseDatabase.serverValueTimestamp || { '.sv': 'timestamp' },
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -9,47 +9,41 @@ import Reference from './reference.js';
|
||||||
* @class Query
|
* @class Query
|
||||||
*/
|
*/
|
||||||
export default class Query extends ReferenceBase {
|
export default class Query extends ReferenceBase {
|
||||||
static ref: Reference;
|
modifiers: Array<DatabaseModifier>;
|
||||||
|
|
||||||
static modifiers: Array<string>;
|
constructor(ref: Reference, path: string, existingModifiers?: Array<DatabaseModifier>) {
|
||||||
|
|
||||||
ref: Reference;
|
|
||||||
|
|
||||||
constructor(ref: Reference, path: string, existingModifiers?: Array<string>) {
|
|
||||||
super(ref.database, path);
|
super(ref.database, path);
|
||||||
this.log.debug('creating Query ', path, existingModifiers);
|
this.log.debug('creating Query ', path, existingModifiers);
|
||||||
this.ref = ref;
|
|
||||||
this.modifiers = existingModifiers ? [...existingModifiers] : [];
|
this.modifiers = existingModifiers ? [...existingModifiers] : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
setOrderBy(name: string, key?: string) {
|
orderBy(name: string, key?: string) {
|
||||||
if (key) {
|
this.modifiers.push({
|
||||||
this.modifiers.push(`${name}:${key}`);
|
type: 'orderBy',
|
||||||
} else {
|
name,
|
||||||
this.modifiers.push(name);
|
key,
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
setLimit(name: string, limit: number) {
|
limit(name: string, limit: number) {
|
||||||
this.modifiers.push(`${name}:${limit}`);
|
this.modifiers.push({
|
||||||
|
type: 'limit',
|
||||||
|
name,
|
||||||
|
limit,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
setFilter(name: string, value: any, key?:string) {
|
filter(name: string, value: any, key?:string) {
|
||||||
if (key) {
|
this.modifiers.push({
|
||||||
this.modifiers.push(`${name}:${value}:${typeof value}:${key}`);
|
type: 'filter',
|
||||||
} else {
|
name,
|
||||||
this.modifiers.push(`${name}:${value}:${typeof value}`);
|
value,
|
||||||
}
|
valueType: typeof value,
|
||||||
|
key,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
getModifiers(): Array<string> {
|
getModifiers(): Array<DatabaseModifier> {
|
||||||
return [...this.modifiers];
|
return [...this.modifiers];
|
||||||
}
|
}
|
||||||
|
|
||||||
getModifiersString(): string {
|
|
||||||
if (!this.modifiers || !Array.isArray(this.modifiers)) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
return this.modifiers.join('|');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,6 +10,8 @@ import { ReferenceBase } from './../base';
|
||||||
import { promisify, isFunction, isObject, tryJSONParse, tryJSONStringify, generatePushID } from './../../utils';
|
import { promisify, isFunction, isObject, tryJSONParse, tryJSONStringify, generatePushID } from './../../utils';
|
||||||
|
|
||||||
const FirebaseDatabase = NativeModules.RNFirebaseDatabase;
|
const FirebaseDatabase = NativeModules.RNFirebaseDatabase;
|
||||||
|
// Unique Reference ID for native events
|
||||||
|
let refId = 1;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @link https://firebase.google.com/docs/reference/js/firebase.database.Reference
|
* @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 {
|
export default class Reference extends ReferenceBase {
|
||||||
|
|
||||||
|
refId: number;
|
||||||
|
listeners: { [listenerId: number]: DatabaseListener };
|
||||||
database: FirebaseDatabase;
|
database: FirebaseDatabase;
|
||||||
query: Query;
|
query: Query;
|
||||||
|
|
||||||
constructor(database: FirebaseDatabase, path: string, existingModifiers?: Array<string>) {
|
constructor(database: FirebaseDatabase, path: string, existingModifiers?: Array<DatabaseModifier>) {
|
||||||
super(database.firebase, path);
|
super(database.firebase, path);
|
||||||
|
this.refId = refId++;
|
||||||
|
this.listeners = {};
|
||||||
this.database = database;
|
this.database = database;
|
||||||
this.namespace = 'firebase:db:ref';
|
this.namespace = 'firebase:db:ref';
|
||||||
this.query = new Query(this, path, existingModifiers);
|
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 path = this.path;
|
||||||
const _value = this._serializeAnyType(value);
|
const _value = this._serializeAnyType(value);
|
||||||
|
|
||||||
return promisify('push', FirebaseDatabase)(path, _value)
|
return promisify('push', FirebaseDatabase)(path, _value)
|
||||||
.then(({ ref }) => {
|
.then(({ ref }) => {
|
||||||
const newRef = new Reference(this.database, 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 successCallback
|
||||||
* @param failureCallback
|
* @param failureCallback
|
||||||
* @param context TODO
|
* @param context TODO
|
||||||
* @returns {*}
|
* @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 (!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');
|
if (failureCallback && !isFunction(failureCallback)) throw new Error('The specified error callback must be a function');
|
||||||
const path = this.path;
|
this.log.debug('adding reference.on', this.refId, eventName);
|
||||||
const modifiers = this.query.getModifiers();
|
const listener = {
|
||||||
const modifiersString = this.query.getModifiersString();
|
listenerId: Object.keys(this.listeners).length + 1,
|
||||||
this.log.debug('adding reference.on', path, modifiersString, eventType);
|
eventName,
|
||||||
this.database.on(path, modifiersString, modifiers, eventType, successCallback, failureCallback);
|
successCallback,
|
||||||
|
failureCallback,
|
||||||
|
};
|
||||||
|
this.listeners[listener.listenerId] = listener;
|
||||||
|
this.database.on(this, listener);
|
||||||
return successCallback;
|
return successCallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param eventType
|
* @param eventName
|
||||||
* @param successCallback
|
* @param successCallback
|
||||||
* @param failureCallback
|
* @param failureCallback
|
||||||
* @param context TODO
|
* @param context TODO
|
||||||
* @returns {Promise.<TResult>}
|
* @returns {Promise.<TResult>}
|
||||||
*/
|
*/
|
||||||
once(eventType: string = 'value', successCallback: (snapshot: Object) => void, failureCallback: (error: Error) => void) {
|
once(eventName: string = 'value', successCallback: (snapshot: Object) => void, failureCallback: (error: FirebaseError) => void) {
|
||||||
const path = this.path;
|
return promisify('once', FirebaseDatabase)(this.refId, this.path, this.query.getModifiers(), eventName)
|
||||||
const modifiers = this.query.getModifiers();
|
|
||||||
const modifiersString = this.query.getModifiersString();
|
|
||||||
return promisify('once', FirebaseDatabase)(path, modifiersString, modifiers, eventType)
|
|
||||||
.then(({ snapshot }) => new Snapshot(this, snapshot))
|
.then(({ snapshot }) => new Snapshot(this, snapshot))
|
||||||
.then((snapshot) => {
|
.then((snapshot) => {
|
||||||
if (isFunction(successCallback)) successCallback(snapshot);
|
if (isFunction(successCallback)) successCallback(snapshot);
|
||||||
|
@ -139,15 +145,37 @@ export default class Reference extends ReferenceBase {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* @param eventType
|
* @param eventName
|
||||||
* @param origCB
|
* @param origCB
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
*/
|
*/
|
||||||
off(eventType?: string = '', origCB?: () => any) {
|
off(eventName?: string = '', origCB?: () => any) {
|
||||||
const path = this.path;
|
this.log.debug('ref.off(): ', this.refId, eventName);
|
||||||
const modifiersString = this.query.getModifiersString();
|
// $FlowFixMe
|
||||||
this.log.debug('ref.off(): ', path, modifiersString, eventType);
|
const listeners: Array<DatabaseListener> = Object.values(this.listeners);
|
||||||
return this.database.off(path, modifiersString, eventType, origCB);
|
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 onComplete
|
||||||
* @param applyLocally
|
* @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.'));
|
if (!isFunction(transactionUpdate)) return Promise.reject(new Error('Missing transactionUpdate function argument.'));
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
|
@ -227,7 +255,7 @@ export default class Reference extends ReferenceBase {
|
||||||
*/
|
*/
|
||||||
orderBy(name: string, key?: string): Reference {
|
orderBy(name: string, key?: string): Reference {
|
||||||
const newRef = new Reference(this.database, this.path, this.query.getModifiers());
|
const newRef = new Reference(this.database, this.path, this.query.getModifiers());
|
||||||
newRef.query.setOrderBy(name, key);
|
newRef.query.orderBy(name, key);
|
||||||
return newRef;
|
return newRef;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -261,7 +289,7 @@ export default class Reference extends ReferenceBase {
|
||||||
*/
|
*/
|
||||||
limit(name: string, limit: number): Reference {
|
limit(name: string, limit: number): Reference {
|
||||||
const newRef = new Reference(this.database, this.path, this.query.getModifiers());
|
const newRef = new Reference(this.database, this.path, this.query.getModifiers());
|
||||||
newRef.query.setLimit(name, limit);
|
newRef.query.limit(name, limit);
|
||||||
return newRef;
|
return newRef;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -308,7 +336,7 @@ export default class Reference extends ReferenceBase {
|
||||||
*/
|
*/
|
||||||
filter(name: string, value: any, key?: string): Reference {
|
filter(name: string, value: any, key?: string): Reference {
|
||||||
const newRef = new Reference(this.database, this.path, this.query.getModifiers());
|
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;
|
return newRef;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -337,6 +365,17 @@ export default class Reference extends ReferenceBase {
|
||||||
return this.path;
|
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
|
* GETTERS
|
||||||
*/
|
*/
|
||||||
|
@ -350,6 +389,14 @@ export default class Reference extends ReferenceBase {
|
||||||
return new Reference(this.database, this.path.substring(0, this.path.lastIndexOf('/')));
|
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 - '/'
|
* Returns a ref to the root of db - '/'
|
||||||
|
|
|
@ -80,7 +80,7 @@ export default class StorageReference extends ReferenceBase {
|
||||||
* Alias to putFile
|
* Alias to putFile
|
||||||
* @returns {StorageReference.putFile}
|
* @returns {StorageReference.putFile}
|
||||||
*/
|
*/
|
||||||
get put() {
|
get put(): Function {
|
||||||
return this.putFile;
|
return this.putFile;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -11,11 +11,13 @@ declare type UploadTaskSnapshotType = {
|
||||||
downloadURL: string|null,
|
downloadURL: string|null,
|
||||||
metadata: Object, // TODO flow type def for https://firebase.google.com/docs/reference/js/firebase.storage.FullMetadata.html
|
metadata: Object, // TODO flow type def for https://firebase.google.com/docs/reference/js/firebase.storage.FullMetadata.html
|
||||||
ref: StorageReference,
|
ref: StorageReference,
|
||||||
state: StorageStatics.TaskState.RUNNING
|
state: (
|
||||||
|StorageStatics.TaskState.PAUSED
|
typeof StorageStatics.TaskState.RUNNING
|
||||||
|StorageStatics.TaskState.SUCCESS
|
| typeof StorageStatics.TaskState.PAUSED
|
||||||
|StorageStatics.TaskState.CANCELLED
|
| typeof StorageStatics.TaskState.SUCCESS
|
||||||
|StorageStatics.TaskState.ERROR,
|
| typeof StorageStatics.TaskState.CANCELLED
|
||||||
|
| typeof StorageStatics.TaskState.ERROR
|
||||||
|
),
|
||||||
task: StorageTask,
|
task: StorageTask,
|
||||||
totalBytes: number,
|
totalBytes: number,
|
||||||
};
|
};
|
||||||
|
@ -24,15 +26,26 @@ declare type FuncSnapshotType = null|(snapshot: UploadTaskSnapshotType) => any;
|
||||||
|
|
||||||
declare type FuncErrorType = null|(error: Error) => any;
|
declare type FuncErrorType = null|(error: Error) => any;
|
||||||
|
|
||||||
declare type NextOrObserverType = null
|
declare type NextOrObserverType = null |
|
||||||
|{ next?: FuncSnapshotType, error?: FuncErrorType, complete?:FuncSnapshotType }
|
{
|
||||||
|FuncSnapshotType;
|
next?: FuncSnapshotType,
|
||||||
|
error?: FuncErrorType,
|
||||||
|
complete?:FuncSnapshotType
|
||||||
|
} |
|
||||||
|
FuncSnapshotType;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @url https://firebase.google.com/docs/reference/js/firebase.storage.UploadTask
|
* @url https://firebase.google.com/docs/reference/js/firebase.storage.UploadTask
|
||||||
*/
|
*/
|
||||||
export default class StorageTask {
|
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.type = type;
|
||||||
this.ref = storageRef;
|
this.ref = storageRef;
|
||||||
this.storage = storageRef.storage;
|
this.storage = storageRef.storage;
|
||||||
|
@ -49,13 +62,13 @@ export default class StorageTask {
|
||||||
* @returns {Promise.<T>}
|
* @returns {Promise.<T>}
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
_interceptSnapshotEvent(f: Function|null|undefined): null|() => any {
|
_interceptSnapshotEvent(f: ?Function): null | () => * {
|
||||||
if (!isFunction(f)) return null;
|
if (!isFunction(f)) return null;
|
||||||
return (snapshot) => {
|
return (snapshot) => {
|
||||||
const _snapshot = Object.assign({}, snapshot);
|
const _snapshot = Object.assign({}, snapshot);
|
||||||
_snapshot.task = this;
|
_snapshot.task = this;
|
||||||
_snapshot.ref = this.ref;
|
_snapshot.ref = this.ref;
|
||||||
return f(_snapshot);
|
return f && f(_snapshot);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -65,12 +78,13 @@ export default class StorageTask {
|
||||||
* @returns {*}
|
* @returns {*}
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
_interceptErrorEvent(f: Function|null|undefined): null|() => any {
|
_interceptErrorEvent(f: ?Function): null | (Error) => * {
|
||||||
if (!isFunction(f)) return null;
|
if (!isFunction(f)) return null;
|
||||||
return (error) => {
|
return (error) => {
|
||||||
const _error = new Error(error.message);
|
const _error = new Error(error.message);
|
||||||
|
// $FlowFixMe
|
||||||
_error.code = error.code;
|
_error.code = error.code;
|
||||||
return f(_error);
|
return f && f(_error);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -83,15 +97,41 @@ export default class StorageTask {
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
_subscribe(nextOrObserver: NextOrObserverType, error: FuncErrorType, complete: FuncSnapshotType): Function {
|
_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);
|
if (typeof nextOrObserver === 'function') {
|
||||||
const _next = this._interceptSnapshotEvent(observer ? nextOrObserver.next : nextOrObserver);
|
_error = this._interceptErrorEvent(error);
|
||||||
const _complete = this._interceptSnapshotEvent(observer ? nextOrObserver.complete : complete);
|
_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 (_next) {
|
||||||
if (_error) this.storage._addListener(this.path, `${this.type}_failure`, _error);
|
this.storage._addListener(
|
||||||
if (_complete) this.storage._addListener(this.path, `${this.type}_success`, _complete);
|
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 () => {
|
return () => {
|
||||||
if (_next) this.storage._removeListener(this.path, StorageStatics.TaskEvent.STATE_CHANGED, _next);
|
if (_next) this.storage._removeListener(this.path, StorageStatics.TaskEvent.STATE_CHANGED, _next);
|
||||||
|
|
12
package.json
12
package.json
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "react-native-firebase",
|
"name": "react-native-firebase",
|
||||||
"version": "1.0.0-alpha12",
|
"version": "1.0.1",
|
||||||
"author": "Invertase <contact@invertase.io> (http://invertase.io)",
|
"author": "Invertase <contact@invertase.io> (http://invertase.io)",
|
||||||
"description": "A react native firebase library supporting both android and ios native firebase SDK's",
|
"description": "A react native firebase library supporting both android and ios native firebase SDK's",
|
||||||
"main": "index",
|
"main": "index",
|
||||||
|
@ -9,7 +9,12 @@
|
||||||
"dev": "npm run compile -- --watch",
|
"dev": "npm run compile -- --watch",
|
||||||
"lint": "eslint ./src",
|
"lint": "eslint ./src",
|
||||||
"publish_pages": "gh-pages -d public/",
|
"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"
|
"flow": "flow"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
|
@ -72,7 +77,8 @@
|
||||||
"flow-bin": "^0.40.0",
|
"flow-bin": "^0.40.0",
|
||||||
"react": "^15.3.0",
|
"react": "^15.3.0",
|
||||||
"react-dom": "^15.3.0",
|
"react-dom": "^15.3.0",
|
||||||
"react-native": "^0.42.0"
|
"react-native": "^0.42.0",
|
||||||
|
"wml": "0.0.82"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"bows": "^1.6.0",
|
"bows": "^1.6.0",
|
||||||
|
|
|
@ -0,0 +1,9 @@
|
||||||
|
{
|
||||||
|
"presets": [
|
||||||
|
"react-native"
|
||||||
|
],
|
||||||
|
"ignore": [
|
||||||
|
"node_modules/diff/lib/**/*.js",
|
||||||
|
"node_modules/diff/node_modules/**/*.js"
|
||||||
|
]
|
||||||
|
}
|
|
@ -0,0 +1,6 @@
|
||||||
|
|
||||||
|
[android]
|
||||||
|
target = Google Inc.:Google APIs:23
|
||||||
|
|
||||||
|
[maven_repositories]
|
||||||
|
central = https://repo1.maven.org/maven2
|
|
@ -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
|
|
@ -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
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,47 @@
|
||||||
|
[ignore]
|
||||||
|
; We fork some components by platform
|
||||||
|
.*/*[.]android.js
|
||||||
|
|
||||||
|
; Ignore "BUCK" generated dirs
|
||||||
|
<PROJECT_ROOT>/\.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='^~\/\(.*\)$' -> '<PROJECT_ROOT>/\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
|
|
@ -0,0 +1 @@
|
||||||
|
*.pbxproj -text
|
|
@ -0,0 +1 @@
|
||||||
|
{}
|
|
@ -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
|
||||||
|
```
|
|
@ -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;
|
|
@ -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;
|
|
@ -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;
|
|
@ -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;
|
|
@ -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;
|
|
@ -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;
|
|
@ -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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
|
@ -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;
|
|
@ -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;
|
|
@ -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;
|
|
@ -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;
|
|
@ -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;
|
|
@ -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;
|
|
@ -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',
|
||||||
|
],
|
||||||
|
)
|
|
@ -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'
|
|
@ -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"
|
||||||
|
}
|
|
@ -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 <methods>; }
|
||||||
|
-keepclassmembers class * { @com.facebook.react.uimanager.UIProp <fields>; }
|
||||||
|
-keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp <methods>; }
|
||||||
|
-keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup <methods>; }
|
||||||
|
|
||||||
|
-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.**
|
|
@ -0,0 +1,51 @@
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
package="com.reactnativefirebasedemo"
|
||||||
|
android:versionCode="1"
|
||||||
|
android:versionName="1.0">
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
|
<uses-permission android:name="android.permission.VIBRATE" />
|
||||||
|
|
||||||
|
<uses-sdk
|
||||||
|
android:minSdkVersion="16"
|
||||||
|
android:targetSdkVersion="22" />
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:name=".MainApplication"
|
||||||
|
android:allowBackup="true"
|
||||||
|
android:icon="@drawable/ic_launcher"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:launchMode="singleTop"
|
||||||
|
android:theme="@style/AppTheme">
|
||||||
|
<service
|
||||||
|
android:name="io.invertase.firebase.messaging.MessagingService"
|
||||||
|
android:enabled="true"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="com.google.firebase.MESSAGING_EVENT" />
|
||||||
|
</intent-filter>
|
||||||
|
</service>
|
||||||
|
|
||||||
|
<service android:name="io.invertase.firebase.messaging.InstanceIdService" android:exported="false">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
|
||||||
|
</intent-filter>
|
||||||
|
</service>
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:windowSoftInputMode="adjustResize">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
|
||||||
|
</application>
|
||||||
|
|
||||||
|
</manifest>
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
@ -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";
|
||||||
|
}
|
||||||
|
}
|
|
@ -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<ReactPackage> getPackages() {
|
||||||
|
return Arrays.<ReactPackage>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);
|
||||||
|
}
|
||||||
|
}
|
Binary file not shown.
After Width: | Height: | Size: 5.1 KiB |
Binary file not shown.
After Width: | Height: | Size: 3.0 KiB |
Binary file not shown.
After Width: | Height: | Size: 7.1 KiB |
Binary file not shown.
After Width: | Height: | Size: 11 KiB |
Binary file not shown.
After Width: | Height: | Size: 16 KiB |
|
@ -0,0 +1,3 @@
|
||||||
|
<resources>
|
||||||
|
<string name="app_name">ReactNativeFirebaseDemo</string>
|
||||||
|
</resources>
|
|
@ -0,0 +1,8 @@
|
||||||
|
<resources>
|
||||||
|
|
||||||
|
<!-- Base application theme. -->
|
||||||
|
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
|
||||||
|
<!-- Customize your theme here. -->
|
||||||
|
</style>
|
||||||
|
|
||||||
|
</resources>
|
|
@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -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
|
Binary file not shown.
|
@ -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
|
|
@ -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 "$@"
|
|
@ -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
|
|
@ -0,0 +1,8 @@
|
||||||
|
keystore(
|
||||||
|
name = 'debug',
|
||||||
|
store = 'debug.keystore',
|
||||||
|
properties = 'debug.keystore.properties',
|
||||||
|
visibility = [
|
||||||
|
'PUBLIC',
|
||||||
|
],
|
||||||
|
)
|
|
@ -0,0 +1,4 @@
|
||||||
|
key.store=debug.keystore
|
||||||
|
key.alias=androiddebugkey
|
||||||
|
key.store.password=android
|
||||||
|
key.alias.password=android
|
|
@ -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'
|
Binary file not shown.
After Width: | Height: | Size: 21 KiB |
|
@ -0,0 +1,5 @@
|
||||||
|
import { AppRegistry } from 'react-native';
|
||||||
|
import bootstrap from './src/main';
|
||||||
|
|
||||||
|
|
||||||
|
AppRegistry.registerComponent('ReactNativeFirebaseDemo', () => bootstrap);
|
|
@ -0,0 +1,4 @@
|
||||||
|
import { AppRegistry } from 'react-native';
|
||||||
|
import bootstrap from './src/main';
|
||||||
|
|
||||||
|
AppRegistry.registerComponent('ReactNativeFirebaseDemo', () => bootstrap);
|
|
@ -0,0 +1,40 @@
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>AD_UNIT_ID_FOR_BANNER_TEST</key>
|
||||||
|
<string>ca-app-pub-3940256099942544/2934735716</string>
|
||||||
|
<key>AD_UNIT_ID_FOR_INTERSTITIAL_TEST</key>
|
||||||
|
<string>ca-app-pub-3940256099942544/4411468910</string>
|
||||||
|
<key>CLIENT_ID</key>
|
||||||
|
<string>305229645282-22imndi01abc2p6esgtu1i1m9mqrd0ib.apps.googleusercontent.com</string>
|
||||||
|
<key>REVERSED_CLIENT_ID</key>
|
||||||
|
<string>com.googleusercontent.apps.305229645282-22imndi01abc2p6esgtu1i1m9mqrd0ib</string>
|
||||||
|
<key>API_KEY</key>
|
||||||
|
<string>AIzaSyAcdVLG5dRzA1ck_fa_xd4Z0cY7cga7S5A</string>
|
||||||
|
<key>GCM_SENDER_ID</key>
|
||||||
|
<string>305229645282</string>
|
||||||
|
<key>PLIST_VERSION</key>
|
||||||
|
<string>1</string>
|
||||||
|
<key>BUNDLE_ID</key>
|
||||||
|
<string>com.invertase.ReactNativeFirebaseDemo</string>
|
||||||
|
<key>PROJECT_ID</key>
|
||||||
|
<string>rnfirebase-b9ad4</string>
|
||||||
|
<key>STORAGE_BUCKET</key>
|
||||||
|
<string>rnfirebase-b9ad4.appspot.com</string>
|
||||||
|
<key>IS_ADS_ENABLED</key>
|
||||||
|
<true/>
|
||||||
|
<key>IS_ANALYTICS_ENABLED</key>
|
||||||
|
<false/>
|
||||||
|
<key>IS_APPINVITE_ENABLED</key>
|
||||||
|
<false/>
|
||||||
|
<key>IS_GCM_ENABLED</key>
|
||||||
|
<true/>
|
||||||
|
<key>IS_SIGNIN_ENABLED</key>
|
||||||
|
<true/>
|
||||||
|
<key>GOOGLE_APP_ID</key>
|
||||||
|
<string>1:305229645282:ios:7b45748cb1117d2d</string>
|
||||||
|
<key>DATABASE_URL</key>
|
||||||
|
<string>https://rnfirebase-b9ad4.firebaseio.com</string>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
|
@ -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
|
|
@ -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
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue