React Native & Socket.io - cannot establish connection between app and server - android

I am building a chat app for android using React Native & Socket.io.
The issue is that I can't establish a connection between the app and the server. It gives me a connection error saying Websocket Error.
I tried changing the App Socket Io URI to localhost: port (this gives transport error or timeout error), ip: port (this gives Websocket error), set diff options. Then tried using require syntaxes instead of import for the server. Then installed older versions React-native and socket.io & socket.io-client, still no luck! Then found an app repo from github, installed it, and tried running the app. same error. Also changed cleartextTrafficPermitted="true" in Android manifest file.
Node: v12.13.0
Testing on external devices:
Moto E3(1s gen) -Android 6 Marshmallow.
Redmi Note 7 Pro -Android 9 Pie
screenshot
SERVER:
import express, { Application } from 'express';
import { createServer } from 'http';
import { listen, Server } from 'socket.io';
// set port number
const port = 7777;
// set express
const app: Application = express();
// set express server
const server = createServer(app);
// listen express server updates on socket.io
const io: Server = listen(server, {
transports: ['websocket'],
serveClient: false,
});
io.on('connection', (socket) => {
console.log('connection is made');
socket.emit('commEvent', { data: 'connectionSuccessful' });
socket.on('disconnect', () => {
console.log('connection disconnected');
});
socket.on('new-message', (data) => {
console.log(data.message);
});
});
// listen server updates on specified port
server.listen(port, () => {
console.log('Message app server listening on port:', port);
});
SERVER: package.json
{
"name": "message_app",
"version": "1.0.0",
"description": "Message app server.",
"main": "index.js",
"scripts": {
"start": "node build/index.js",
"watch": "nodemon src/index.ts",
"test": "none",
"build": "npm run lint && tsc-p",
"lint": "eslint --fix --ext .ts ."
},
"dependencies": {
"express": "^4.17.1",
"socket.io": "^2.3.0"
},
"devDependencies": {
"#types/express": "^4.17.6",
"#types/socket.io": "^2.1.8",
"#typescript-eslint/eslint-plugin": "^3.3.0",
"#typescript-eslint/parser": "^3.3.0",
"eslint": "^7.2.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.4",
"nodemon": "^2.0.4",
"prettier": "^2.0.5",
"ts-node": "^8.10.2",
"typescript": "^3.9.5"
}
}
APP:
import React, {useEffect} from 'react';
import {AppScreenStackNavProps} from '../../../Routes/App/AppRouteTypes';
import {View} from 'react-native';
import HomeRoutes from '../../../Routes/Home/HomeRoute';
import io from 'socket.io-client';
export const socket = io('http://192.168.1.38:7777', {
transports: ['websocket'],
jsonp: false,
});
socket.on('commEvent', (data: {data: string}) => {
console.warn(data.data);
});
const HomeScreen = ({navigation}: AppScreenStackNavProps<'Home'>) => {
navigation.setOptions({
headerShown: false,
});
useEffect(() => {
socket.connect();
socket.on('connect', (con: any) => {
console.debug('SOCKET: connected to socket server', con);
});
socket.on('error', (err: any) => {
console.debug('SOCKET: errors ', err);
});
socket.on('connect_error', (err: any) => {
console.debug('SOCKET: connect_error ---> ', err);
});
}, []);
return (
<>
<View style={{flex: 1}}>
<HomeRoutes />
</View>
</>
);
};
export default HomeScreen;
APP: package.json
{
"name": "message_app",
"version": "1.0.0",
"description": "Message app server.",
"main": "index.js",
"scripts": {
"start": "node build/index.js",
"watch": "nodemon src/index.ts",
"test": "none",
"build": "npm run lint && tsc-p",
"lint": "eslint --fix --ext .ts ."
},
"dependencies": {
"express": "^4.17.1",
"socket.io": "^2.3.0"
},
"devDependencies": {
"#types/express": "^4.17.6",
"#types/socket.io": "^2.1.8",
"#typescript-eslint/eslint-plugin": "^3.3.0",
"#typescript-eslint/parser": "^3.3.0",
"eslint": "^7.2.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.4",
"https-localhost": "^4.6.0",
"nodemon": "^2.0.4",
"prettier": "^2.0.5",
"ts-node": "^8.10.2",
"typescript": "^3.9.5"
}
}

I spend a day on this issue what i find is the problem is with your module you installed.
That means if you use typescript in your project make sure to add .d.ts file also for the "socket.io.client" module.
or use this same code in javascript.

Related

Error while creating elasticsearch firebase firestore cloud function

I am trying to create a cloud function which will be responsible of sending every new entry into the database to the elasticsearch server.
This is what my index.js looks like
const functions = require('firebase-functions');
const request = require('request-promise');
exports.indexUsersToElastic = functions.firestore
.document('users/{id}')
.onWrite(event => {
let userData = event.data.val();
let user_id = event.params.user_id;
console.log('Indexing user:' userData);
let elasticSearchConfig = functions.config().elasticsearch;
let elasticSearchUrl = elasticSearchConfig.url + 'users/user/' + id;
let elasticSearchMethod = postData ? 'POST' : 'DELETE';
let elasticSearchRequest = {
method: elasticSearchMethod,
url: elasticSearchUrl,
auth: {
username: elasticSearchConfig.username,
password: elasticSearchConfig.password,
},
body: userData,
json: true
};
return request(elasticSearchRequest).then(response => {
console.log("ElasticSearch response", response);
});
});
And this is what my package.json looks like
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint --ext ./index.js",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "16"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^10.0.2",
"firebase-functions": "^3.18.0"
},
"devDependencies": {
"eslint": "^8.19.0",
"firebase-functions-test": "^0.2.0",
"tslint": "^6.1.3"
},
"private": true
}
On running firebase deploy --only functions
I get this
Running command: npm --prefix "$RESOURCE_DIR" run lint
> lint
> eslint --ext ./index.js
✔ functions: Finished running predeploy script.
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
✔ functions: required API cloudfunctions.googleapis.com is enabled
✔ functions: required API cloudbuild.googleapis.com is enabled
i functions: preparing codebase default for deployment
Error: Failed to load function definition from source: Failed to generate manifest from function source: SyntaxError: missing ) after argument list
Can anyone navigate me through the problem and its solution?

Receiving Proxy error: Error occurred while proxying request [ECONNREFUSED] in react app

I have a react application that is making API calls through axios to my backend and I am receiving the error
[HPM] Error occurred while proxying request matt.hearthdisplay.com:3000/api/user/my to http://localhost:8000/ [ECONNREFUSED] (https://nodejs.org/api/errors.html#errors_common_system_errors)
I am not even calling proxy in my package.json so I am not sure why it's even attempting this? For context the API GET requests are working on my coworker's machines with the same code and I have recently moved to a new location with a different wifi router so I am not sure if this is a computer-specific problem.
matt.hearthdisplay.com:3000/api/user/my is my front end react app and http://localhost:8000/ is for my backend.
What could be causing this? I am on a Macbook M1 running Mac OS Montery 12.3 below are my files that should help. I have tried everything online I have found...
API Request thats producing the error
useEffect(() => {
async function inner() {
const response = await axiosClient.get(`/user/my`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.status === 200) {
setFormState({
firstName: response.data.user.first_name,
lastName: response.data.user.last_name,
});
}
}
if (!!token) {
inner();
}
}, [token]);
axiosCLient.ts
import axios, { AxiosResponse } from "axios";
import { apiRoot } from "./variables";
const axiosClient = axios.create({
baseURL: apiRoot,
});
// Timeout in 3 seconds by default
axiosClient.defaults.timeout = 3000;
function handle2xxResponse(response: AxiosResponse<any>): AxiosResponse<any> {
return response;
}
axiosClient.interceptors.response.use(handle2xxResponse);
export default axiosClient;
package.json
{
"name": "webapp",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.7.1",
"#emotion/styled": "^11.6.0",
"#fortawesome/fontawesome-svg-core": "^1.2.36",
"#fortawesome/free-solid-svg-icons": "^5.15.4",
"#fortawesome/react-fontawesome": "^0.1.16",
"#fullhuman/postcss-purgecss": "^4.1.3",
"#mui/icons-material": "^5.2.4",
"#mui/material": "^5.2.4",
"#mui/styled-engine-sc": "^5.1.0",
"#sentry/react": "^6.16.1",
"#sentry/tracing": "^6.16.1",
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"#types/jest": "^26.0.15",
"#types/node": "^12.0.0",
"#types/react": "^17.0.0",
"#types/react-dom": "^17.0.0",
"#types/react-lottie": "^1.2.6",
"axios": "^0.24.0",
"http-proxy-middleware": "^2.0.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-hook-form": "^7.21.2",
"react-lottie": "^1.2.3",
"react-native-dropdown": "^0.0.6",
"react-router-dom": "^6.0.2",
"react-scripts": "4.0.3",
"styled-components": "^5.3.3",
"tailwindcss": "^2.2.19",
"typescript": "^4.1.2",
"web-vitals": "^1.0.1",
"zustand": "^3.6.5"
},
"scripts": {
"build:tailwind": "postcss src/styles/index.tailwind.css -o src/styles/index.css",
"watch:tailwind": "postcss -w src/styles/index.tailwind.css -o src/styles/index.css",
"start": "run-p watch:tailwind start:react",
"start:react": "react-scripts start",
"prebuild": "npm run build:tailwind",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"autoprefixer": "^10.4.0",
"npm-run-all": "^4.1.5",
"postcss": "^8.4.4",
"postcss-cli": "^9.0.2"
}
}
setUpProxy.js
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
createProxyMiddleware("/api", {
target: "http://localhost:8000",
changeOrigin: true,
secure: false,
})
);
};
Trying add the following header in the proxy code;
target: "http://localhost:8000",
headers: {
"Connection": "keep-alive"
},
...
The Keep-Alive general header allows the sender to hint about how the connection may be used to set a timeout and a maximum amount of requests.

Switch from react-native 0.59.9 to 0.66.0 and native-base in a new instance

Since I had a very dated app, react-native 0.59.9 + native-base 2.10.0, or decided to update it starting from a clean project using the classic:
npx react-native init AwesomeProject
at this point I also installed the new native-base 3.2.1 and I overturned all the files and updated their dependencies, many things were different, especially those related to react-navigation.
Once the dependencies have been resolved, the compilation takes place correctly, as seen from the metro bundler (react-native start) but the application immediately crashes reporting:
Require cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle.
ERROR TypeError: undefined is not an object (evaluating 'Comp.displayName')
ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.
ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.
I tried to clear the cache, delete node_modules and recreate it but the error always appears.
From what I understand there is some problem with the appRegistry in the early stage, these are my files where I assume something abnormal is happening.
app.json
{
"name": "MyApp",
"displayName": "MyApp"
}
index.js
import {AppRegistry, Text, TextInput } from 'react-native';
import App from './App';
import {name as appName} from './app.json';
//Disable the FontScaling set by the device (Component "Text").
Text.defaultProps = Text.defaultProps || {};
Text.defaultProps.allowFontScaling = false;
//Disable the FontScaling set by the device (Component "TextInput").
TextInput.defaultProps = Text.defaultProps || {};
TextInput.defaultProps.allowFontScaling = false;
AppRegistry.registerComponent(appName, () => App);
App.js
import React from 'react';
import Setup from './src/boot/setup.js';
export default class App extends React.Component {
render() {
return (
<Setup/>
);
}
}
./src/boot/setup.js (here I inserted the NativeBaseProvider component which was not used before.)
import React from 'react';
import { NativeBaseProvider } from 'native-base';
import App from '../App.js';
export default class Setup extends React.Component {
render() {
return (
<NativeBaseProvider>
<App />
</NativeBaseProvider>
);
}
}
./src/App.js
import React from 'react';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import { createDrawerNavigator } from '#react-navigation/drawer';
import { createSwitchNavigator } from "#react-navigation/compat";
import Home from './components/Home/homeScreen';
import Login from './components/Login/loginScreen';
import ResetPassword from './components/Login/resetPassword';
import News from './components/News/newsScreen';
import Chat from './components/Chat/chatScreen';
import ProfileIndex from './components/Profile/profileIndex';
import SideBar from './components/sidebar/sidebar';
import NewsDetails from './components/News/newsScreenDetails';
import Privacy from './components/Privacy/privacyScreen';
import SignUpWorker from './components/SignUpWorker/signUpWorker';
import AuthLoadingScreen from './utils/authLoadingScreen';
const SignedInDrawer = createDrawerNavigator(
{
Home: { screen: Home },
ProfileIndex: { screen: ProfileIndex },
Chat: { screen: Chat },
News: { screen: News },
NewsDetails: { screen: NewsDetails },
Privacy: { screen: Privacy },
},
{
initialRouteName: 'Home',
contentComponent: props => <SideBar {...props} />,
}
);
const SignedOutDrawer = createDrawerNavigator(
{
Home: { screen: Home },
Login: { screen: Login },
ResetPassword: { screen: ResetPassword },
SignUp: { screen: SignUp },
News: { screen: News },
NewsDetails: { screen: NewsDetails },
Privacy: { screen: Privacy },
},
{
initialRouteName: 'Home',
contentComponent: props => <SideBar {...props} />,
}
);
const SignedInStack = createNativeStackNavigator(
{
DrawerIn: { screen: SignedInDrawer },
},
{
initialRouteName: 'DrawerIn',
headerMode: 'none',
}
);
const SignedOutStack = createNativeStackNavigator(
{
DrawerOut: { screen: SignedOutDrawer },
},
{
initialRouteName: 'DrawerOut',
headerMode: 'none',
}
);
export default createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen,
SignedIn: SignedInStack,
SignedOut: SignedOutStack,
},
{
initialRouteName:'AuthLoading'
}
);
./src/utils/authLoadingScreen.js
import { View, ActivityIndicator, StyleSheet, StatusBar, NetInfo } from 'react-native';
import AsyncStorage from '#react-native-async-storage/async-storage';
import React from 'react';
export let globalUserToken;
export let globalNetworkOnline;
// this function is used to set the globalUserToken from other pages
export function setglobalUserToken(newValue: boolean) {
globalUserToken = newValue;
}
export async function checkNetwork() {
await NetInfo.getConnectionInfo().then(connectionInfo => {
if (connectionInfo.type === 'none') {
globalNetworkOnline = false;
} else {
globalNetworkOnline = true;
}
});
}
export default class AuthLoadingScreen extends React.Component {
constructor() {
super();
this._bootstrapAsync();
}
// Fetch the token from storage then navigate to our appropriate place
_bootstrapAsync = async () => {
globalUserToken = await AsyncStorage.getItem('id_token');
// This will switch to the App screen or Auth screen and this loading
// screen will be unmounted and thrown away.
this.props.navigation.navigate(globalUserToken ? 'SignedIn' : 'SignedOut');
};
render() {
return (
<View style={styles.container}>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
The problem most likely starts from src/App.js as i have updated the functions for createNativeStackNavigator, createDrawerNavigator, createSwitchNavigator which were previously simply StackNavigator, DrawerNavigator, SwitchNavigator from 'react-navigation'.
Or the error resides in ./src/utils/authLoadingScreen.js where it is checked if a login token exists... maybe something has changed here too?
Finally I leave you my package.json:
{
"name": "MyApp",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint .",
"build:ios": "react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios",
"build:android": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res"
},
"dependencies": {
"#react-native-async-storage/async-storage": "^1.15.9",
"#react-navigation/compat": "^5.3.20",
"#react-navigation/drawer": "^6.1.8",
"#react-navigation/native": "^6.0.6",
"#react-navigation/native-stack": "^6.2.4",
"#types/react-native-dotenv": "^0.2.0",
"native-base": "^3.2.1",
"react": "17.0.2",
"react-native": "0.66.0",
"react-native-dotenv": "^3.2.0",
"react-native-gesture-handler": "^1.10.3",
"react-native-htmlview": "^0.16.0",
"react-native-reanimated": "2.3.0-beta.2",
"react-native-safe-area-context": "^3.3.2",
"react-native-screens": "^3.8.0",
"react-native-size-matters": "^0.4.0",
"react-native-svg": "^12.1.1",
"rn-fetch-blob": "^0.12.0",
"styled-components": "^5.3.1",
"styled-system": "^5.1.5",
"tcomb-form-native": "^0.6.20"
},
"devDependencies": {
"#babel/core": "^7.12.9",
"#babel/runtime": "^7.15.4",
"#react-native-community/eslint-config": "^2.0.0",
"babel-jest": "^27.2.5",
"eslint": "^8.0.1",
"jest": "^27.2.5",
"metro-react-native-babel-preset": "^0.66.2",
"react-test-renderer": "17.0.2"
},
"jest": {
"preset": "react-native"
}
}
Has anyone had this problem or do you know if I have correctly changed the components of react-navigation no longer used in the new version?

Error setting up firebase with react possible unhandled promise rejection

I am currently creating a food ordering system and i am trying to set up firebase on a react-native project
The application lets me use authentication from firebase i can succesfully sign in and also register new users but it does not let me use firestore
i am trying to do a console log in the below code in my to see if the firestore will run with the application
below is a list of the app.js/the screen where i am calling the collection from firestore
the error reads as so
firebase error
//error reads on android emulator
the build.gradle app level and the
//list of packages used on for react
package.json
"name": "projectFinal",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"#react-native-community/masked-view": "^0.1.7",
"#react-native-firebase/app": "^6.3.4",
"#react-native-firebase/auth": "^6.3.4",
"#react-native-firebase/firestore": "^6.3.4",
"firebase": "^7.9.3",
"react": "16.9.0",
"react-native": "0.60.5",
"react-native-elements": "^1.2.7",
"react-native-gesture-handler": "^1.6.0",
"react-native-reanimated": "^1.7.0",
"react-native-safe-area-context": "^0.7.3",
"react-native-safe-area-view": "^1.0.0",
"react-native-screens": "^2.2.0",
"react-native-vector-icons": "^6.6.0",
"react-navigation": "^4.2.2",
"react-navigation-header-buttons": "^3.0.5",
"react-navigation-stack": "^2.2.2",
"react-navigation-tabs": "^2.8.2"
},
"devDependencies": {
"#babel/core": "^7.8.6",
"#babel/runtime": "^7.8.4",
"#react-native-community/eslint-config": "^0.0.7",
"babel-jest": "^25.1.0",
"eslint": "^6.8.0",
"jest": "^25.1.0",
"metro-react-native-babel-preset": "^0.58.0",
"react-test-renderer": "16.9.0"
},
"jest": {
"preset": "react-native"
}
}
app.js
import React, { Component } from 'react';
import { View, StyleSheet, Text } from 'react-native';
import {createAppContainer, createSwitchNavigator} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import {createBottomTabNavigator, createTabNavigator} from 'react-navigation-tabs'
import Icon from 'react-native-vector-icons/Ionicons'
import { HeaderButtons, HeaderButton, Item } from 'react-navigation-header-buttons';
import Home from './src/Screens/Home'
//import MyAccount from './Screens/MyAccount';
import Register from './src/Screens/Register'
import Login from './src/Screens/Login';
//import Menus from './Screens/Menus';
import LoadingScreen from './src/Screens/LoadingScreen';
// import Jitters from './Screens/Jitters';
// import Scullery from './Screens/Scullery';
// import Bunker from './Screens/TheBunker';
// import OrderDetails from './Screens/OrderDetails';
import ViewOrder from './src/Screens/ViewOrder';
import "firebase/firestore"
import firebase from "firebase"
import firestore from "#react-native-firebase/firestore"
//this is where firebase is initializedd the google.services json is also in the relevant file
const firebaseConfig = {
apiKey: "AIza<<redacted>>",
authDomain: "<<redacted>>.firebaseapp.com",
databaseURL: "https://<<redacted>>.firebaseio.com",
projectId: "<<redacted>>",
storageBucket: "<<redacted>>.appspot.com",
messagingSenderId: "<<redacted>>",
appId: "1:8<<redacted>>",
measurementId: "G-T<<redacted>>"
};
// Instantiate a Firebase app.
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore()
const TabNavigator = createBottomTabNavigator(
{
Home: {
screen: Home,
navigationOptions: {
TabBarIcon: ({ tintColor}) => <Ionicons name="ios-home" size={24} color={tintColor}/>
}
},
// Menus: {
// screen: Menus,
// navigationOptions: {
// TabBarIcon: ({ tintColor}) => <Ionicons name="ios-chatbox" size={24} color={tintColor}/>
// }
ViewOrder: {
screen: ViewOrder,
navigationOptions: {
TabBarIcon: ({ tintColor}) => <Ionicons name="ios-add-circle" size={24} color={tintColor}/>
},
}
},
{
tabBarOptions: {
activeTintColor: "#161F3D",
inactiveTintColor: "#E9446A",
showLabel: true
}
}
);
const authStack = createStackNavigator(
{
Home: Home,
Login: Login,
Register: Register,
// Menu: Menus,
// Jitters: Jitters,
// Scullery: Scullery,
// TheBunker: Bunker,
// MyAccount: MyAccount,
// OrderDetails: OrderDetails,
ViewOrder: ViewOrder
});
const App = createAppContainer(TabNavigator);
export default createAppContainer(
(
createSwitchNavigator({
Loading: LoadingScreen,
App: TabNavigator,
Auth: authStack
},
{
initalRouteName: "Loading Page"
}
)
)
);
##Screen to call a collection of firestore##
//this is a console log to see if firestore will initialize
import React, {useState} from 'react'
import {View, Text} from 'react-native'
import firebase from "firebase"
import firestore from "#react-native-firebase/firestore"
async function myFunction() {
var user = firebase.auth().currentUser;
let x = await firestore().collection("Users").doc("MmjyeGlhFPu0g6pK0GQ2").get();
// console.log(x)
}
export default class ViewOrder extends React.Component {
componentDidMount() {
myFunction(
)
}
render() {
return(
<View>
<Text>Hello</Text>
</View>
)}
**//error reads on android emulator**
as possible unhandled promise rejection (id:0)
error: no firebase app ['default] has been created - call
firebase.initalize.app() getapp#http://10.0.2.2.8081/index.bundle
?platform
It seems by the error, mainly for this below part:
Error: No Firebase App '[DEFAULT]' has been created - call firebase.initializeApp()
That you have not initialized your Firebase database. As informed in the documentation firebase. app. App, you need to call firebase.initializeApp() to create an app. Besides that, I would change your import to import * as firebase from "firebase", so you are importing all packages needed for Firebase.
I have checked all these below posts from the Community and these possible solutions that I provided you, are just some options and alternatives that might solve your case.
I would recommend you take a look at them, so you can get more information and check further since there might be some other structure and environment configurations that can be affecting you and these cases can assist you with it.
No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()
Firebase: No Firebase App '[DEFAULT]' has been created (Firestore)
Error: Firebase: No Firebase App '[DEFAULT]' has been created
Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()
Let me know if the information helped you!

Platform specific testing using Jest on a React Native app

This is the react native component
//Test.js
export default class Test extends Component {
render() {
return(
<View>
</Animated.View> {
Platform.OS === 'android' &&
<TouchableNativeFeedback>
// some android specific code
</TouchableNativeFeedback>
}</Animated.View>
</View>
)
}
}
THis is the test case;
//testcases.js
import { Text, TouchableOpacity, Platform } from 'react-native';
import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';
import Test from '../Test'
describe('Testing an App', () => {
let snapshot;
beforeAll(() => {
snapshot = shallow(<Test />);
Platform.OS = 'android';
});
it(' -- must return 1', () => {
expect(snapshot.find('TouchableNativeFeedback').length).toBe(1);
});
});
While the expected return is 1; The received value is 0; I have set up Platform as 'android' and yet no luck.
I am new to Mobile automation testing; Hence I could be missing something obvious. Should I use react-dom to render and test further?
I feel it's something very obvious, but can't get my finger on it.
This is my package.json
{
"name": "exampleApp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "15.4.1",
"react-native": "0.42.3"
},
"devDependencies": {
"babel-jest": "20.0.3",
"babel-preset-react-native": "2.0.0",
"jest": "20.0.4",
"enzyme" : "2.8.0",
"react-dom": "15.4.1",
"react-addons-test-utils":"15.4.1",
"react-test-renderer": "15.4.1"
},
"jest": {
"preset": "react-native"
}
}
You can not change your platform directly in your test. You need to set the desired platform in your settings. Take a look at this documentation to see how to do it.

Categories

Resources