How do you detox test offline mode - react-native

We're developing a react native app and building automated testing with detox on CI.
I am wondering how to test the offline mode of the app with detox ? Has anyone already tried this ?

I found a workaround for android emulator :
export function setNetworkConnection(boolean: boolean) {
child.exec(
"adb shell svc data " +
`${boolean ? "disable;" : "enable;"}` +
"adb shell svc wifi " +
`${boolean ? "disable;" : "enable;"}`,
function (error, stdout, stderr) {
if (error !== null) {
console.log(stdout, stderr);
console.log("child.exec error: " + error);
}
}
);
}

Related

Working with env variables in React Native for iOS app

I'm having a heck of a time getting env variables to work correctly for a React Native app. I develop locally testing on web and Expo, and then my aim is to publish to the App Store.
At first, I tried using react-native-dotenv, but while it seemed fine locally, prod settings wouldn't take hold when I did a formal Expo build to run either on iOS Simulator or submit to App Store.
So I abandoned that and went with a suggestion from the Expo documentation around creating a Config.js file, as so:
const { manifest } = Constants;
if (Platform.OS == 'web') {
if (Updates.channel === 'production') {
Config.ENV_NAME = 'production';
Config.BACKEND_URL = '[...]';
Config.HIDDEN_FEATURES = false;
} else if (Updates.channel === 'preview') {
Config.ENV_NAME = 'preview'
Config.BACKEND_URL = '[...]';
Config.HIDDEN_FEATURES = false;
} else if (Updates.channel === 'development') {
Config.ENV_NAME = 'development';
Config.BACKEND_URL = 'http://localhost:3000/';
Config.HIDDEN_FEATURES = true;
}
} else if (Platform.OS == 'ios') {
[Repeat of above, but with different values as needed]
}
Elsewhere in my app, I would try to use this like so:
import Config from '../Config';
console.log("Backend URL: " + Config.BACKEND_URL + ", env: " + Config.ENV_NAME)
The problem is - this didn't seem to work at all! Any of the Config keys just didn't yield anything. When trying to debug this, I got other parts of the code to log Updates.channel and looks like that wasn't working anywhere (neither web nor ios), so nothing got set.
Questions...
Is there a solid recommended way to do env variables in React Native for an iOS app? I've seen so many different choices but hard to tell if one's the most common / recommended
Am I doing something wrong with the attempt to use Config.js above?

Expo BackgroundFetch not working on android when app is terminated

The task gets registered it also works.When in recent apps it works.When gets deleted it stops working!
Expo CLI 3.11.3 environment info:
System:
OS: Windows 10
Binaries:
Yarn: 1.21.0 - C:\Users\Steve\AppData\Roaming\npm\yarn.CMD
npm: 6.9.0 - E:\Program Files\nodejs\npm.CMD
IDEs:
Android Studio: Version 3.5.0.0 AI-191.8026.42.35.5900203
SDK version : 36.0.0
Standalone app on android 7
Just to confirm I was right I went into my apps background in my setting in my phone,I can see the app is in background progress.As soon as I remove it from recent apps it gets gone from the background progress too.So everything is as I described and no doubts about it.I also have used:
stopOnTerminate: false,
But it doesn’t do anything.
Here’s a function that does register the tasks and everything:
import * as BackgroundFetch from 'expo-background-fetch';
import * as TaskManager from 'expo-task-manager';
export async function registerFetchTask(taskName, jobCallback, interval) {
TaskManager.defineTask(taskName, jobCallback);
const status = await BackgroundFetch.getStatusAsync();
switch (status) {
case BackgroundFetch.Status.Restricted:
case BackgroundFetch.Status.Denied:
console.log("Background execution is disabled");
return;
default: {
console.log("Background execution allowed");
let tasks = await TaskManager.getRegisteredTasksAsync();
if (tasks.find(f => f.taskName === taskName) == null) {
console.log("Registering task");
await BackgroundFetch.registerTaskAsync(taskName,{
minimumInterval: 60,
stopOnTerminate: false,
startOnBoot: true,
});
tasks = await TaskManager.getRegisteredTasksAsync();
console.log("Registered tasks", tasks);
} else {
console.log(`Task ${taskName} already registered, skipping`);
}
console.log("Setting interval to", interval);
await BackgroundFetch.setMinimumIntervalAsync(interval);
}
}
}
Inside app.js I call:
registerFetchTask('wow',()=>{
fetchServer('/test',{});
console.log('WOWWW HIIIIIIIII YGNNNNNN');
},5);
The fetchServer will add things to my database on my laptop.So I can see if the app is running the task I’m getting new rows in the database.

How to get URL with loadstart event in app browser in ionic 4 for instagram api?

I try to get URL with inAppBrowser in ionic 4 for my instagram api. I build PWA and smartphone applications. . Why loadstart event
does not work when I build in PWA ?
I've already tried to get with in app browser plugin for ionic4 and with javascript (window.open() method).
In app Browser work when I build my IOS app.
That doesn't work when I build my PWA app/
//instagram API
let authUrl = `https://www.instagram.com/oauth/authorize/?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=token&scope=public_content`;
//create in app browser
var browser = this.iab.create(authUrl, '_blank');
//test loadstart event
browser.on('loadstart').subscribe(event => {
alert('loadstart');
alert(event.url);
}, err => {
alert("InAppBrowser loadstart Event Error: " + err);
});
//test loadstop event
browser.on('loadstop').subscribe(event => {
alert('loadstop');
alert(event.url);
}, err => {
alert("InAppBrowser loadstop Event Error: " + err);
});
}
PWA output :
loadstop
event.url == ""
IOS output :
loadstart
event.url == url
loadstop
event.url == ""
Thank you :)
inAppBrowser is a cordova plugin it will work fine in android & ios App, but pwa is completely web app it will not support cordova plugin, So it's better to show it in a component it will work fine.

How to show native popup using Gulp

I am working on Gulp build process for automation. I have created a Gulp task for creating signed APK of android. Now I want to show a notification popup so that I can come to know my android APK is built.
Is there any way to show native popup in Gulp process?
I have done research and found node-notifier and gulp-notify modules but both are not working for me. Please help
As per posted answer,
I have tried with following, but no help... I am not getting notification. Does it requires Windows Toaster Support... I am using Windows 8.1 Pro.
gulp.task('notifier', function(){
notify('Running from notifier task', 'Everything looks good');
});
function notify(title, message) {
// Load dependencies
var path = require('path');
var notifier = require('node-notifier');
var notifyOptions = {
title: title,
message: message,
//icon: path.join(__dirname, 'coulson.jpg'), // Absolute path (doesn't work on balloons)
sound: true, // Only Notification Center or Windows Toasters
wait: true // Wait with callback, until user action is taken against notification
};
// start notifier
notifier.notify(notifyOptions);
}
Try this:
Make sure these are installed by running install once again
Install
npm install path node-notifier --save-dev
Task
gulp.task('notifier', function(){
notify('Running from notifier task', 'Everything looks good');
);
Notifier Function
function notify(title, message) {
// Load dependencies
var path = require('path');
var notifier = require('node-notifier');
var notifyOptions = {
title: title,
message: message,
icon: path.join(__dirname, 'coulson.jpg'), // Absolute path (doesn't work on balloons)
sound: true, // Only Notification Center or Windows Toasters
wait: true // Wait with callback, until user action is taken against notification
};
// start notifier
notifier.notify(notifyOptions);
}
This is too late after asking the question, but I thought it's good to record my solutions here.
So there are different commands to show a native popup for different OS.
1. Windows
Use the command msg * <Your_Message_Here>, for example, msg * Hello World.
This popup closes automatically after 1 minute.
2.iOS
Use the command
osascript -e 'tell app \"System Events\" to display dialog \"<Your_Message>\" with title \"<Your_Title>\"'"
and then you can execute these commands using node exec,
var WINDOWS_POPUP = "msg * MESSAGE";
var MAC_POPUP = "osascript -e 'tell app \"System Events\" to display dialog \"MESSAGE\" with title \"SUCCESS\"'";
function execCMD(cmd, cb) {
exec(cmd,
{
cwd: './',
maxBuffer: 2048 * 2048
},
function (err, stdout, stderr) {
plugins.util.log(stdout);
plugins.util.log(stderr);
if (err) {
cb(err);
} else {
cb(null,stdout);
}
});
}
/**
* Rename android apk
*/
gulp.task('copyAPK', function () {
return gulp.src(APK_PATH)
.pipe(plugins.if(args.signedAPK, plugins.rename(APK_NAME)))
.pipe(gulp.dest(releaseDirName + '/Android/'))
.on('end', function () {
plugins.util.log(plugins.util.colors.green('Good Job! Your APK is ready at following location : ') + plugins.util.colors.cyan(releaseDirName + '/Android/' + APK_NAME))
execCMD(WINDOWS_POPUP.replace('MESSAGE', 'Good Job! Your APK is ready at following location : ' + releaseDirName + '/Android/' + APK_NAME), function () {
})
});
});
/**
* Copy generated IPA
*/
gulp.task('copyIPA', function () {
return gulp.src(IPA_PATH)
.pipe(plugins.rename(IPA_NAME))
.pipe(gulp.dest(releaseDirName + '/iOS/'))
.on('end', function () {
plugins.util.log(plugins.util.colors.green('Good Job! Your IPA is ready at following location : ') + plugins.util.colors.cyan(releaseDirName + '/iOS/' + IPA_NAME))
execCMD(MAC_POPUP.replace('MESSAGE', 'Good Job! Your IPA is ready at following location : ' + releaseDirName + '/iOS/' + IPA_NAME), function () {
})
});
})
Hope this will help someone in scripting :).

Push notification with Appcelerator (ACS) on Android

I'm trying to implement push notification with Appcelerator Cloud Service on Android But I have some issues ... tiapp.xml here :
<sdk-version>2.0.2.GA</sdk-version>
<modules>
<module platform="commonjs" version="2.0.5">ti.cloud</module>
<module platform="android" version="2.0.5">ti.cloudpush</module>
</modules>
Android runtime v8 and ti.cloudpush included, here is my app.js file
var win = Ti.UI.createWindow({
backgroundColor:'#ccc',
title:'Android Cloud Push Notification'
})
var CloudPush = require('ti.cloudpush');
CloudPush.debug = true;
CloudPush.enabled = true;
CloudPush.showTrayNotificationsWhenFocused = true;
CloudPush.focusAppOnPush = false;
var deviceToken;
var Cloud = require('ti.cloud');
Cloud.debug = true;
var submit = Ti.UI.createButton({
title : 'Register For Push Notification',
color:'#000',
height : 53,
width : 200,
top : 100,
});
win.add(submit);
submit.addEventListener('click', function(e) {
CloudPush.retrieveDeviceToken({
success: function deviceTokenSuccess(e) {
alert('Device Token: ' + e.deviceToken);
deviceToken = e.deviceToken
loginDefault();
},
error: function deviceTokenError(e) {
alert('Failed to register for push! ' + e.error);
}
});
});
function defaultSubscribe(){
Cloud.PushNotifications.subscribe({
channel: 'chanel',
device_token: deviceToken,
type: 'android'
}, function (e){
if (e.success) {
alert('Subscribed for Push Notification!');
}else{
alert('Error:' +((e.error && e.message) || JSON.stringify(e)));
}
});
}
function loginDefault(e){
//Create a Default User in Cloud Console, and login
Cloud.Users.login({
login: 'android',
password: 'android'
}, function (e) {
if (e.success) {
alert("login success");
defaultSubscribe();
} else {
alert('Error: ' +((e.error && e.message) || JSON.stringify(e)));
}
});
}
CloudPush.addEventListener('callback', function (evt) {
//alert(evt);
alert(evt.payload);
});
CloudPush.addEventListener('trayClickLaunchedApp', function (evt) {
//Ti.API.info('Tray Click Launched App (app was not running)');
alert('Tray Click Launched App (app was not running');
});
CloudPush.addEventListener('trayClickFocusedApp', function (evt) {
//Ti.API.info('Tray Click Focused App (app was already running)');
alert('Tray Click Focused App (app was already running)');
});
win.open();
I had the user android / android in the Appcelerator cloud console for the development mode. Launched my app to my device with debogage mode
On the app : Just click on the button "register for push notification" and see 3 alerts
1) Device Token : " all numbers "
2) login success
3) Subscribed for Push Notification!
On the Appcelerator Cloud console :
Logs -> see login & subscribe, opened it and everything's ok
Push Notifications -> 1 Android clients subscribed to push notifications. And send one throught push notifications with alert & title
And nothing appears at all ... try reboot, try to turn the app off and send another one, nothing.
I was using a device (LG OPTIMUS ONE) with android 2.2.1 with internet on it (wifi). So, I tried with another phone (SAMSUNG GALAXY S2) 3.3.2 with internet on it (wifi)
And the only change is in the cloud console :
Push Notifications -> 2 Android clients subscribed to push notifications.
But it is the same, no notification appears.
Please, I really need help for this, I succeed with iOS in 2 days and I do not understand what is the big deal here ?
I don't think I need to register with Google C2DM for using ACS.
ACS use MQTT protocol for sending push.
(I followed this step by step tut : http://www.titaniumtutorial.com/2012/06/appcelerator-cloud-push-notification-in.html)
Have you already done one project with push notification on Android & Ti ?
I checked my settings and everything is fine.
But, because I'm desperate, I also register to C2DM and nothing better, I guess I have to wait a bit more before testing.
I use the upush module in the Marketplace, took me 10 minutes to gtet it up and running, saved me loads of time.
Have you registered with Google C2DM? You need to fill out the form at https://developers.google.com/android/c2dm/signup to send notifications to the device. Make sure you have your correct App ID in the Appcelerator Cloud Settings.