I have 3 tabs, that I need to test if they are clicked or not, but I can't seem to find a good expected condition to use. Right now I am using a browser. sleep with higher times, since the tab takes a couple of seconds to load.
The tabs:
Code:
let locator = {
upcomingTabButton : element(by.css('div.toolbar-content.toolbar-content-md ion-segment ion-segment-button:nth-child(1)')),
pendingTabButton : element(by.css('div.toolbar-content.toolbar-content-md ion-segment ion-segment-button:nth-child(2)')),
completedTabButton : element(by.css('div.toolbar-content.toolbar-content-md ion-segment ion-segment-button:nth-child(3)')),
activeTab : element(by.css('ion-segment ion-segment-button.segment-button.segment-activated')),
upcomingActiveTab: element(by.cssContainingText('ion-segment ion-segment-button.segment-button.segment-activated', 'UPCOMING')),
};
describe('When x tab button is pressed, ', function () {
it('if x = PENDING tab, then it should be activated', () => {
browser.sleep(1000);
browser.wait(EC.elementToBeClickable(locator.pendingTabButton),5000);
locator.pendingTabButton.click();
browser.sleep(10000);
expect(element(by.css('ion-segment ion-segment-button.segment-button.segment-activated')).getText()).toEqual('PENDING');
});
it('if x = UPCOMING tab, then it should be activated', () => {
browser.wait(EC.elementToBeClickable(locator.upcomingTabButton),5000);
locator.upcomingTabButton.click();
//browser.wait(EC.presenceOf(locator.upcomingActiveTab),5000);
browser.sleep(10000);
expect(element(by.css('ion-segment ion-segment-button.segment-button.segment-activated')).getText()).toEqual('UPCOMING');
});
it('if x = COMPLETED tab, then it should be activated', () => {
browser.wait(EC.elementToBeClickable(locator.completedTabButton),5000);
locator.completedTabButton.click();
//browser.wait(EC.presenceOf(locator.activeTab),5000);
browser.sleep(10000);
expect(element(by.css('ion-segment ion-segment-button.segment-button.segment-activated')).getText()).toEqual('COMPLETED');
});
});
I tried some expected conditions but nothing worked since I need to see when the tab is selected and I didn't found any exp condition like that.
I am using the browser.sleep(10000) 10 seconds, but that's, not a good way to use.
Can anyone help me here?
The tabs content takes like 5/6 seconds to load
/**
* wait until some element is present
*
*/
this.waitElement = function(ElmFinder){
var i = 0;
var _retryOnErr = function(err) {
console.log(' <<< warning: wait retrying iteration: ' + i + ' >>> ');
browser.sleep(500);
return false;
};
browser.wait(function() {
i++;
return ElmFinder.isDisplayed().then(function(present) {
if (present) {
return true;
} else {
console.log("element is not present");
return _retryOnErr();
}
}, _retryOnErr);
}, 120*1000, 'Error waiting for element present: ').
then(function(waitRetValue) {
return waitRetValue; // usually just `true`
}, function(err) {
throw err + ' after ' + i + ' iterations.';
});
};
Related
I'm trying to write in a characteristic that sends a binary file as the value, this value is large, it's 19215 bytes which is not a problem because i negociated the mtu using :
device.connect({ requestMTU: 260 })
i've divided the file into 240 bytes for each element and each time encode the element to base64 and i use the function writeCharacteristicWithResponseForDevice() in order to write that element,
the issue is i successfully wrote the whole file 19215 bytes using a loop to write each time an element, but while i tried to read the characteristic i can only read the last written element
Example:
this.manager.writeCharacteristicWithResponseForDevice(device.id,"1111", "40E1ED56-EC4A-4DC6-A6BD-30377F186B77", base64.encode(element1)
this.manager.writeCharacteristicWithResponseForDevice(device.id,"1111", "40E1ED56-EC4A-4DC6-A6BD-30377F186B77", base64.encode(element2))
this.manager.writeCharacteristicWithResponseForDevice(device.id,"1111", "40E1ED56-EC4A-4DC6-A6BD-30377F186B77", base64.encode(element3))
when i read the Characteristic using
device.readCharacteristicForService("1111", "40E1ED56-EC4A-4DC6-A6BD-30377F186B77")
i get as a value :
console.log(base64.decode(characteristic.value) => element3
it should be element1+ element2 + element3
-
here is my code for writing :
WriteIncaracteristic() {
// this.state.fileSize is calculated in another function
const nbPackages = Math.floor(this.state.fileSize/240) + 1
var fileArray = []
for (let i = 0; i <= nbPackages; i++) {
// this.state.fileContent is created in another function
fileArray.push(this.state.fileContent.slice(0, 240))
this.state.fileContent = this.Remove(this.state.fileContent, 0, 240)
}
for (let j = 0; j <= fileArray.length; j++) {
if (fileArray[j]) {
const device = this.state.myDevice
this.manager.writeCharacteristicWithResponseForDevice(device.id,"1111","40E1ED56-EC4A-4DC6-A6BD-30377F186B77", base64.encode(fileArray[j]))
.then((characteristic) => {
console.log(base64.decode(characteristic.value));
return
}) .catch((error) => {
this.createTAlert("writing", error.message )
});
}}
}
here is the function to read characteristic:
ReadCaracteristic() {
const device = this.state.myDevice
device.readCharacteristicForService("1111", "40E1ED56-EC4A-4DC6-A6BD-30377F186B77")
.then((characteristic) => {
console.log(base64.decode(characteristic.value));
console.log(characteristic );
return
}) .catch((error) => {
// Handle errors
this.createTAlert("Reading", error.message )
});
}
Can anybody help please by providing a working example in how to send large package files, because the problem can be while writing, the function erases the older value maybe.
Thanks
I have an odd issue I can't explain the reason for it - maybe someone here can shed some light on it
I have a ticket scanning app in Xamarin Forms currently testing it on android
the interface allows you to:
type an order number and click the check order Button
use the camera scanner to scan which automatically triggers check order
use the barcode scanner to scan which automatically triggers check order
after the check order validation, user has to select the number of tickets from a drop down list and press confrim entry button
what I'm trying to do, is if the seats available on that ticket is just 1 - then automatically trigger confirm entry button functionality
problem that I have is that - some of my logic depends on setting the drop down index in code - for some reason it doesn't update - as seen in the debugger shot here
and this is the second tme I've noticed this today, earlier it was a var I was trying to assign a string and it kept coming up as null - eventually I replaced that code
is this a bug in xamarin ?
code has been simplified:
async void OnCheckOrderButtonClicked(object sender, EventArgs e)
{
await ValidateOrderEntry();
}
private async void scanCameraButton_Clicked(object sender, EventArgs e)
{
messageLabel.Text = string.Empty;
var options = new ZXing.Mobile.MobileBarcodeScanningOptions();
options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
ZXing.BarcodeFormat.QR_CODE,ZXing.BarcodeFormat.EAN_8, ZXing.BarcodeFormat.EAN_13
};
var scanPage = new ZXingScannerPage(options);
scanPage.OnScanResult += (result) =>
{
//stop scan
scanPage.IsScanning = false;
Device.BeginInvokeOnMainThread(async () =>
{
//pop the page and get the result
await Navigation.PopAsync();
orderNoEntry.Text = result.Text;
//automatically trigger update
await ValidateOrderEntry();
});
};
await Navigation.PushAsync(scanPage);
}
private async Task ValidateOrderEntry()
{
//...other code....
checkInPicker.Items.Clear();
if (availablTickets == 1)
{
checkInPickerStack.IsVisible = true;
checkInPicker.SelectedIndex = 0;
messageLabel.Text = "Ticket OK! - " + orderNoEntry.Text;
messageLabel.TextColor = Color.Green;
//select the only element
checkInPicker.SelectedIndex = 0;
await PostDoorEntry();
}
//...other code....
}
private async Task PostDoorEntry()
{
int entryCount = checkInPicker.SelectedIndex + 1;
//... more code...
//...post api code..
}
Maybe I'm overlooking something, but you clear all the items a few lines above the one you are pointing out. That means there are no items in your Picker and thus you can't set the SelectedIndex to anything other than -1, simply because there are no items.
I came across several questions on this subject. I'm trying to select the rear camera on an Android device running Chrome.
So, after some reading :
var selector = document.getElementById('video-source-selector');
navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
var videoDevices = devices.map(function (item) {
if(item.kind === 'videoinput'){
return item;
}
}).filter(function( element ) {
return element !== undefined;
});
var max = videoDevices.length;
videoDevices.forEach(function(device, i) {
var html = '';
var div = document.createElement('div');
if(i === max-1){ // last element reached
html += '<option value="'+device.deviceId+'" selected>'+ device.label +'</option>';
}
else {
html += '<option value="'+device.deviceId+'">'+ device.label +'</option>';
}
div.innerHTML = html;
selector.appendChild(div.childNodes[0]);
console.log(device.kind + ": " + device.label +
" id = " + device.deviceId);
});
})
.catch(function(err) {
console.log(err.name + ": " + err.message);
});
selector.addEventListener("change", function(){
console.log(selector.value); // Works as supposed : returns the ID of the selected device
});
Then, as I'm using Three.js in this app, I'm binding this ID to Jerome Etienne three extension WebcamGrabbing (https://github.com/jeromeetienne/threex.webar):
var videoGrabbing = new THREEx.WebcamGrabbing(selector.value);
Then I had to modify THREEx.WebcamGrabbing class this way (I removed the irrelevant parts):
THREEx.WebcamGrabbing = function(sourceDeviceId){
...
console.log('webcamgrabbing : ', sourceDeviceId); // returns the expected ID
var constraints = {
video: {
optional: [{
sourceId: sourceDeviceId
}]
}
}
// try to get user media
navigator.getUserMedia( constraints, function(stream){
domElement.src = URL.createObjectURL(stream);
}, function(error) {
console.error("Cant getUserMedia()! due to ", error);
});
...
}
But still, Chrome on Android is still giving me the stream of the face camera, whatever device I select...
What do I miss?
EDIT : Based on this topic (GetUserMedia - facingmode), I came up with some logs to see what's happening here :
var constraints = {
audio: false,
video: { facingMode: { exact: "environment" } }
}
console.log('Try to get stream with constraints:', constraints);
navigator.getUserMedia( constraints, function(stream){
var videoTracks = stream.getVideoTracks();
console.log('Got stream with constraints:', constraints); // Ok
console.log('Using video device: ' + videoTracks[0].label); // > Using video device: camera 0, facing back
for(var i = 0; i < videoTracks.length; i++){
console.log('Found video device with contraints : ', videoTracks[i].label); // Found video device with contraints : camera 0, facing back
}
domElement.src = URL.createObjectURL(stream);
}, function(error) {
console.error("Cant getUserMedia()! due to ", error);
});
An alternative way to select the back camera on chrome is to use the enumerateDevices method.
First get all the video input id's:
navigator.mediaDevices.enumerateDevices().then(function(devices) {
devices.forEach(function(device) {
if(device.kind=="videoinput"){
//If device is a video input add to array.
}
});
Then the first element of the array will contain the id of the front camera, the second element will contain the id of the back camera.
Finally put the id of the camera that you want to use
navigator.getUserMedia({audio: false, video: { sourceId: VideoId } }, successCallback, errorCallback);
I intend to get users geolocation even when the app sits dormant in the background and store the same in the database.
I'm using katzer's Cordova Background Plug-in,
When I try to access navigator.geolocation.getCurrentPosition inside backgroundMode.onactivate function, nothing happens, Whereas when I try passing hard coded values api is called, data is stored in database.
following is my code
document.addEventListener('deviceready', function() {
// Android customization
cordova.plugins.backgroundMode.setDefaults({
text: 'Doing heavy tasks.'
});
// Enable background mode
cordova.plugins.backgroundMode.enable();
// Called when background mode has been activated
cordova.plugins.backgroundMode.onactivate = function() {
console.log('inside background')
a();
}
var a = function() {
console.log('a called')
navigator.geolocation.getCurrentPosition(function(pos) {
console.log('inside navigate');
var data = {
Lati: '123456',
Longi: '132456',
//LoginID: JSON.parse(window.localStorage.getItem('LoginId'))
EmpCode: localStorage.getItem('LoginId')
};
$http.post("https://app.sbismart.com/bo/ContactManagerApi/UpdateEmployeeLoc", data).success(function(rsdata, status) {
console.log('inside rsdata');
console.log(data.Lati + "," + data.Longi);
})
}, function(error) {
alert('Unable to get location: ' + error.message);
});
}
}, false);
cordova.plugins.backgroundMode.onfailure = function(errorCode) {
console.log(errorCode)
};`
and check as to why is it failing....then again u need to run the locationService function in a timeout function in the background to get updated about the location and check the location from previously got location.
Something like this...
cordova.plugins.backgroundMode.onactivate = function () {
setTimeout(function () {
a();
}, 5000);
}
Hope this helps.
I'm using the InAppBrowser plugin (v1.1.1) with Cordova for an OAuth login process. Unfortunately, the InAppBrowser doesn't appear to be closing the browser. My "closeBrowser" function instead continually triggers the interval, and the browser remains on-screen on the Android (I have not tried other devices at this time.)
Is there a way to forcibly close the InAppBrowser other than .close(), or hide it? Or maybe there's a flaw in my code somewhere that is locking the browser.
LogInPage.prototype.handleExternalLogin = function (externalLogin) {
var _this = this;
var ref = window.open(Environment_1.settings.baseUrl + externalLogin.route.url, "_blank", "location=no");
ref.addEventListener('loadstart', function (event) {
if (_.startsWith(event.url, Environment_1.settings.baseUrl + "/api/Account/account/ExternalLoginCallback")) {
// Now we want to load a different url that will give us the mobile access token
console.log('get external-mobile-token');
_this.closeBrowser(ref);
var ref2 = window.open(Environment_1.settings.baseUrl + "/api/Account/external-mobile-token", "_blank" /*, "location=no"*/);
ref2.addEventListener('loadstop', function (event) {
console.log('loadstop ' + event.url);
if (event.url == Environment_1.settings.baseUrl + "/api/Account/external-mobile-token") {
ref2.executeScript({ code: 'window.document.documentElement.innerText' }, function (contents) {
_this.login(contents);
_this.closeBrowser(ref2);
});
}
});
ref2.addEventListener('loaderror', function (event) {
console.log(event);
_this.closeBrowser(ref2);
// TODO - do something?
});
}
});
ref.addEventListener('loaderror', function (event) {
console.log(event);
_this.closeBrowser(ref);
// TODO - do something?
});
};
LogInPage.prototype.closeBrowser = function (browser) {
var interval = setInterval(function () {
console.log('closing');
browser.close();
}, 10);
browser.addEventListener('exit', function () {
console.log('closed');
clearInterval(interval);
});
};
LogInPage.prototype.login = function (token) {
console.log(token);
};
The above code is actually generated from TypeScript, but I figured I wouldn't confuse the issue.
It appears that closing an InAppBrowser and opening another at the same time was causing the issue; rewriting the process to only need one window solved my issue.