How to pass exceptions in Dart? - flutter

I am Currently working with puppeteer Dart package, as you see in this code below.
try {
await page.waitForXPath('//*[#id="confirm-yes"]');
var confirm = await page.$x('//*[#id="confirm-yes"]');
await confirm[0].click();
}catch (e) {
print(e)
}
the code above works fine, i use it on my other tasks, however in this particular step the selector is a popup and it sometimes come up and sometimes doesnt, and so i want it to be like if the popup comes up this above code will identify the selector element and click on it, but if it isnt available than just skip this and move on, however it just gives out an exception and breaks the code. i am very new to dart in python i would have just written pass in exception block.
please help.

Related

How to click on copy button with cypress

So in my app i have a button and when i click on it, it will save some text into my clipboard, then i can past it by ctrl+v somewhere.
And i am trying to write cypress test for this. Problem is, when i click on that button i got cypress error:
I can´t figured out. Element is clearly viewed on page. I tryied to wait few second before clicking and it didn´t help.
Is there a way how to test it?
Thank you for your answers.
Your application has thrown an error, not cypress. To avoid this, you will want to add this either to your test file or /support/index.js. This code was pulled from this example. Remember cy. requires a test or a hook to work, while Cypress. does not.
// inspect the caught error
cy.on('uncaught:exception', (e) => {
if (e.message.includes('Things went bad')) {
// we expected this error, so let's ignore it
// and let the test continue
return false
}
// on any other error message the test fails
})
You can catch exceptions globally by writing this under cypress/support/index.js
Cypress.on('uncaught:exception', (err, runnable) => {
return false
})

Flutter how to mock a call to rootBundle.loadString(...), then reset the mocked behavior?

In my flutter code, I have logic that does this:
final jsonString = await rootBundle.loadString('AssetManifest.json');
And I have tests that I want to return a fake AssetManifest.json when this line is reached.
To mock it, I do this in the test:
ServicesBinding.instance.defaultBinaryMessenger
.setMockMessageHandler('flutter/assets', (message) {
final Uint8List encoded =
utf8.encoder.convert('{"Foo.ttf":["Foo.ttf"]}');
return Future.value(encoded.buffer.asByteData());
});
The weird thing is, this works, but any tests that run after it hang (they all get stuck in the code when it reaches the await rootBundle.loadString('AssetManifest.json') line.
I've tried adding
ServicesBinding.instance.defaultBinaryMessenger
.setMockMessageHandler('flutter/assets', null);
But this doesn't seem to properly "clean up" the mocked behavior. In fact, if I run the above line in my setUp, the first test to run hangs.
So am I mocking the behavior wrong? Or am I not cleaning it up properly?
I ran into the same issue, and believe it's due to caching by the bundle. This will cause the above test to fail, because the message never gets sent. When calling loadString, you can specify whether to cache the result. E.g. loadString('AssetManifest.json', false).
Note that if you use loadStructuredData, implementations can cache the result and you can't tell it not to.

Async/Await/then in Dart/Flutter

I have a flutter application where I am using the SQFLITE plugin to fetch data from SQLite DB. Here I am facing a weird problem. As per my understanding, we use either async/await or then() function for async programming.
Here I have a db.query() method which is conducting some SQL queries to fetch data from the DB. After this function fetches the data, we do some further processing in the .then() function. However, in this approach, I was facing some issues. From where I am calling this getExpensesByFundId(int fundId)function, it doesn't seem to fetch the data properly. It's supposed to return Future> object which will be then converted to List when the data is available. But when I call it doesn't work.
However, I just did some experimentation with it and added "await" keyword in front of the db.query() function and somehow it just started to work fine. Can you explain why adding the await keyword is solving this issue? I thought when using .then() function, we don't need to use the await keyword.
Here are my codes:
Future<List<Expense>> getExpensesByFundId(int fundId) async {
Database db = await database;
List<Expense> expenseList = List();
// The await in the below line is what I'm talking about
await db.query(expTable,where: '$expTable.$expFundId = $fundId')
.then((List<Map<String,dynamic>> expList){
expList.forEach((Map<String, dynamic> expMap){
expenseList.add(Expense.fromMap(expMap));
});
});
return expenseList;
}
In simple words:
await is meant to interrupt the process flow until the async method has finished.
then however does not interrupt the process flow (meaning the next instructions will be executed) but enables you to run code when the async method is finished.
In your example, you cannot achieve what you want when you use then because the code is not 'waiting' and the return statement is processed and thus returns an empty list.
When you add the await, you explicitly say: 'don't go further until my Future method is completed (namely the then part).
You could write your code as follows to achieve the same result using only await:
Future<List<Expense>> getExpensesByFundId(int fundId) async {
Database db = await database;
List<Expense> expenseList = List();
List<Map<String,dynamic>> expList = await db.query(expTable,where: '$expTable.$expFundId = $fundId');
expList.forEach((Map<String, dynamic> expMap) {
expenseList.add(Expense.fromMap(expMap));
});
return expenseList;
}
You could also choose to use only the then part, but you need to ensure that you call getExpensesByFundId properly afterwards:
Future<List<Expense>> getExpensesByFundId(int fundId) async {
Database db = await database;
List<Expense> expenseList = List();
return db.query(expTable,where: '$expTable.$expFundId = $fundId')
.then((List<Map<String,dynamic>> expList){
expList.forEach((Map<String, dynamic> expMap){
expenseList.add(Expense.fromMap(expMap));
});
});
}
// call either with an await
List<Expense> list = await getExpensesByFundId(1);
// or with a then (knowing that this will not interrupt the process flow and process the next instruction
getExpensesByFundId(1).then((List<Expense> l) { /*...*/ });
Adding to the above answers.
Flutter Application is said to be a step by step execution of code, but it's not like that.
There are a lot of events going to be triggered in the lifecycle of applications like Click Event, Timers, and all. There must be some code that should be running in the background thread.
How background work execute:
So there are two Queues
Microtask Queue
Event Queue
Microtask Queue runs the code which not supposed to be run by any event(click, timer, etc). It can contain both sync and async work.
Event Queue runs when any external click event occurs in the application like Click event, then that block execution done inside the event loop.
The below diagram will explain in detail how execution will proceed.
Note: At any given point of application development Microtask queue will run then only Event Queue will be able to run.
When making class use async for using await its simple logic to make a wait state in your function until your data is retrieve to show.
Example: 1) Its like when you follow click button 2) Data first store in database than Future function use to retrieve data 3) Move that data into variable and than show in screen 4) Variable show like increment in your following/profile.
And then is use one by one step of code, store data in variable and then move to next.
Example: If I click in follow button until data store in variable it continuously retrieve some data to store and not allow next function to run, and if one task is complete than move to another.
Same as your question i was also doing experiment in social media flutter app and this is my understanding. I hope this would help.
A Flutter question from an answer from your answer.
await is meant to interrupt the process flow until the async method has finished. then however does not interrupt the process flow but enables you to run code when the async method is finished. So, I am asking diff. between top down & bottom down process in programming.

Try-catch like feature for uncertain code block in Swift 4

I am writing a test in XCUITest. There is an introductory banner which may or may not come on the mobile screen while my test is in progress. I want to write my case in such a way that, if the banner is present, I have to verify certain elements on that banner and click on the "Continue" button on it, and if it is not present, I have to proceed with my test case.
I know in Java, we write such code inside a try-catch block, so that even if the banner is not found and the code fails, the pointer goes into the catch block and the remaining program continues.
When I searched on the internet, i only found such feature for single statements and not for some chunk of code block.Do we have something similar in Swift, where I can write some code inside try-catch like code block?
Please have a look at my test case and the code to click in the banner.
class MyTestClass: BaseTest {
func testMapSearch() {
do {
let app = try XCUIApplication()
let element = try app.children(matching: .window).element(boundBy: 0).children(matching: .other).element.children(matching: .other).element(boundBy: 1).children(matching: .other).element(boundBy: 0)
element.buttons["Continue"].tap()
} catch let error {
print("Error: \(error)")
}
let logInButton = app.scrollViews.otherElements.buttons["Log In"]
checkLoginPage(login: logInButton)
logInButton.tap()
}
}
The do block is written to click on the "Continue" button on a banner which is not sure to be displayed on the screen. The do block is followed by more code. If the banner is not displayed, the code written in the do block fails and the test case throws an error. I want to write a case such that the login button code should get executed irrespective of the banner is displayed or not.
The problem with your code is that the two lines of code marked try are not failable (they don't throw), so you cannot mark them try in the first place.
The entire attempt to turn this situation into a try/catch is wrong-headed. What you want to do here is simply add a condition to check whether the desired element exists and is tappable, and proceed differently if it doesn't (i.e. don't attempt to tap it). That is what if is for.
(Of course one might argue that if the test is not intended to fail if it is impossible to tap this element, then the test itself is incorrectly constructed — you should just omit the tap line altogether.)

How to stop automatically closing browser when writing protractor test cases

I am new to writing test cases using protractor for non angular application. I wrote a sample test case.Here the browser closes automatically after running test case.How can I prevent this. Here is my code
var submitBtnElm = $('input[data-behavior=saveContribution]');
it('Should Search', function() {
browser.driver.get('http://localhost/enrollments/osda1.html');
browser.driver.findElement(by.id('contributePercentValue')).sendKeys(50);
submitBtnElm.click().then(function() {
});
});
I was also struggling with a similar issue where i had a test case flow where we were interacting with multiple application and when using Protractor the browser was closing after executing one conf.js file. Now when I looked into the previous response it was like adding delay which depends on how quick your next action i performed or it was hit or miss case. Even if we think from debugging perspective most of the user would be performing overnight runs and they would want to have browser active for couple of hours before they analyze the issue. So I started looking into the protractor base code and came across a generic solution which can circumvent this issue, independent of any browser. Currently the solution is specific to requirement that browser should not close after one conf.js file is executed, then could be improved if someone could add a config parameter asking the user whether they want to close the browser after their run.
The browser could be reused for future conf.js file run by using tag --seleniumSessionId in command line.
Solution:
Go to ..\AppData\Roaming\npm\node_modules\protractor\built where your
protractor is installed.
Open driverProvider.js file and go to function quitDriver
Replace return driver.quit() by return 0
As far as my current usage there seems to be no side effect of the code change, will update if I came across any other issue due to this change. Snapshot of code snippet below.
Thanks
Gleeson
Snapshot of code snippet:
Add browser.pause() at the end of your it function. Within the function itself.
I found Gleeson's solution is working, and that really helped me. The solution was...
Go to %APPDATA%Roaming\npm\node_modules\protractor\built\driverProviders\
Find driverProviders.js
Open it in notepad or any other text editor
Find and Replace return driver.Quit() to return 0
Save the file
Restart your tests after that.
I am using
node v8.12.0
npm v6.4.1
protractor v5.4.1
This solution will work, only if you installed npm or protractor globally; if you have installed your npm or protractor locally (in your folder) then, you have to go to your local protractor folder and do the same.
I suggest you to use browser.driver.sleep(500); before your click operation.
See this.
browser.driver.sleep(500);
element(by.css('your button')).click();
browser.driver.sleep(500);
Add a callback function in It block and the browser window doesn't close until you call it.
So perform the action that you need and place the callback at your convenience
var submitBtnElm = $('input[data-behavior=saveContribution]');
it('Should Search', function(callback) {
browser.driver.get('http://localhost/enrollments/osda1.html');
browser.driver.findElement(by.id('contributePercentValue')).sendKeys(50);
submitBtnElm.click().then(function() {
// Have all the logic you need
// Then invoke callback
callback();
});
});
The best way to make browser NOT to close for some time, Use browser.wait(). Inside the wait function write logic for checking either visibilityOf() or invisibilityOf() of an element, which is not visible or it will take time to become invisible on UI. In this case wait() keep on checking the logic until either condition met or timeout reached. You can increase the timeout if you want browser visible more time.
var EC=protractor.ExpectedConditions;
var submitBtnElm = $('input[data-behavior=saveContribution]');
it('Should Search', function() {
browser.driver.get('http://localhost/enrollments/osda1.html');
browser.driver.findElement(by.id('contributePercentValue')).sendKeys(50);
submitBtnElm.click().then(function() {
browser.wait(function(){
EC.invisibilityOf(submitBtnElm).call().then(function(isPresent){
if(isPresent){
return true;
}
});
},20000,'error message');
});
});
I'm sure there is a change triggered on your page by the button click. It might be something as subtle as a class change on an element or as obvious as a <p></p> element with the text "Saved" displayed. What I would do is, after the test, explicitly wait for this change.
[...]
return protractor.browser.wait(function() {
return element(by.cssContainingText('p', 'Saved')).isPresent();
}, 10000);
You could add such a wait mechanism to the afterEach() method of your spec file, so that your tests are separated even without the Protractor Angular implicit waits.
var submitBtnElm = $('input[data-behavior=saveContribution]');
it('Should Search', function() {
browser.driver.get('http://localhost/enrollments/osda1.html');
browser.driver.findElement(by.id('contributePercentValue')).sendKeys(50);
submitBtnElm.click().then(function() {
});
browser.pause(); // it should leave browser alive after test
});
browser.pause() should leave browser alive until you let it go.
#Edit Another approach is to set browser.ignoreSynchronization = true before browser.get(...). Protractor wouldn't wait for Angular loaded and you could use usual element(...) syntax.
Protractor will close browsers, that it created, so an approach that I am using is to start the browser via the webdriver-reuse-session npm package.
DISCLAIMER: I am the author of this package
It is a new package, so let me know if it solves your problem. I am using it with great success.