In one of our tests, sometimes we get the browser alert message when the user is trying to log out.
I do not want the tests failed due to these alerts. We are getting the below error when there is an alert:
An error was thrown in an afterAll
AfterAll Failed: unexpected alert open: {Alert text : You have unsaved changes! If you leave, your changes will be lost.}
I have tried to resolve it by
1. added unexpectedAlertBehaviour: 'accept' to the conf.js file, which failed, and 2, modifying the code using an if/else block as follows:
exports.logOutfromESY =function(){
var G = GV;
var EC = protractor.ExpectedConditions;
expect(G.User_Menu_Dropdown.isPresent()).toBeTruthy();
G.User_Menu_Dropdown.click();
browser.wait(EC.presenceOf(G.logOut_Button), 2000, 'The Logout Buttons taking too long to appear in the DOM');
G.logOut_Button.click();
browser.sleep(500);
if(alert.isPresent()){
browser.switchTo().alert().then(function (alert) {
alert.accept();
});
}
browser.wait(EC.presenceOf(G.Email_Input_box), 3000, 'The Login Page redirection taking long time');
browser.sleep(500);
};
It did not work either. Note that the "alert" variable was my last ditch effort to make protractor to identify the alert.
Is there any way to achieve this?
Seems that this solution may be helpful:
https://stackoverflow.com/a/29873887/6331748
EDIT:
You can also consider to use --disable-notifications flag.
You need to add it in your config file like that:
export const config = {
capabilities: {
chromeOptions: {
args: ['--disable-notifications']
}
}
}
Related
My objective: Test out my error handling functionality.
Temporary solution: Have a custom route: /error, which contains code which purposefully produces fatal error.
var a = undefined;
a.b.c // Breaks.
The above works, but I can't use it to test production site as the page is not required.
I was looking for a way to test it via the browser. I tried simply adding"
throw new Error("Custom error thrown here") to the console. That doesn't actually break it during runtime.
I tried adding a break point and adding the same code: throw new Error("Custom error thrown here"). That didn't work either.
Any other easier ways to do this rather than the above?
I was looking for a way where I can do it via browser only.
Thanks.
You did not clearly mention how and where the error should be thrown. I will assume that you can use a modified copy of your JavaScript file to throw errors. The modified file will reside on your computer and only be used when you're using Chrome developer tools. This feature is called Local Overrides. The steps are as follows:
Open the webpage
Open Chrome developer tools for that webpage
In Sources panel go to Overrides tab
Click Select folder for overrides and choose a folder on your computer
A warning appears on the webpage which reads "DevTools requests full access to ..." which you must allow
In Sources panel go to Page tab
Locate the file in which you need to inject the "throw error" code
Right click and choose Save for overrides
Now you can edit the copy of the file on your computer or from within developer tools. Insert the code that produces the error at the desired location. When you reload the page with developer tools open, Chrome will load the local copy of the JavaScript file and throw the error. The error thrown that way will contain the context from where it originated e.g. call stack. If the developer tools are closed then live copy will be used.
If I got your question right, this is How you can do it from the console:
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'throw new Error("Custom error thrown here")';
document.body.appendChild(script_tag);
Or if you want you can trigger it on click:
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'window.document.onclick = function() { throw new Error("Custom error thrown here")}';
document.body.appendChild(script_tag);
And then you click anywhere on the page, to throw the error;
I would use the exec function which actually takes string and runs the code within at compile time.
exec('a.b.c')
You won't be able to throw an error inside your application from the console, since you are out of scope of the app.
Having said that, one slightly awkward way you could do this is by adding a breakpoint at the start of the javascript file.
Reload the page and your app will pause at the breakpoint - you can then modify the code as you need - like adding a throw new Error("something...") - and save your edits.
Then allow the code to run and you will see your error.
A downside is if you reload the changes will be gone, but I believe it's as close as you can get to modifying code at runtime.
Add this code to your production code
window.addEventListener('err', () => {
throw new Error('break it');
})
and when you want to create an error simply
dispatchEvent(new Event('err'))
in the console
You can use a global variable, which is accessible from your app and from debug console.
if (window.shouldThrow) {
throw new Error("Custom error thrown here");
}
This way you can turn on/off the exception throwing using the window.shouldThrow variable.
Try this way to catch error detail on run time
try
{
var a = undefined;
a.b.c // Breaks.
}
catch ( e )
{
alert("Error: " + e.description );
}
Not able to play Video using Test Cafe, Click event is not playing video. I am able to hover till specific element but when i click it should start playing the video. But it is unable to play.
const logger = RequestLogger({ url: 'URL', method: 'post' },
{ logResponseBody: true, logRequestBody: true, stringifyResponseBody: true, stringifyRequestBody: true });
const obj = 'URL';
await t.navigateTo(obj.uri);
const loader = Selector('.web_player_loader.loader');
await t.expect(loader.exists).notOk({ timeout: 30000 });
console.log('Video Started....');
const playerBase=Selector('.player-base');
await t.hover(playerBase);
await t.click(playerBase);
console.log('Logger Request Length is ',logger.requests.length);```
I am running the script using following params.
testcafe chrome --autoplay-policy=no-user-gesture-required ./tests -s takeOnFails=true --skip-js-errors=true
Getting this error in the Console.
main.dad0fa6441f0af49d386.js:2 Uncaught (in promise) TypeError: Cannot read property 'topLPVs' of undefined
at t.value (main.dad0fa6441f0af49d386.js:2)
at e.value (main.dad0fa6441f0af49d386.js:2)
at e.value (main.dad0fa6441f0af49d386.js:2)
at t.<anonymous> (main.dad0fa6441f0af49d386.js:2)
at l (vendor~main.58.ac1d1027b98ee8b3b2d1.js:9)
at Generator._invoke (vendor~main.58.ac1d1027b98ee8b3b2d1.js:9)
at Generator.next (vendor~main.58.ac1d1027b98ee8b3b2d1.js:9)
at n (hammerhead.js:15)
at value (hammerhead.js:6)
at n (vendor~main.58.ac1d1027b98ee8b3b2d1.js:2)
at a (vendor~main.58.ac1d1027b98ee8b3b2d1.js:2)
According to the callstack you provided, it looks like the error occurs in your application. This behavior can occur because testcafe clicks faster than an end user and initialization code on the tested page might not have sufficient time to complete. Could you please clarify if the same error occurs if you add a delay between hover and click actions?
t.hover(playerBase)
.wait(1000)
.click(playerBase);
If the error is reproduced, could you share an example showing it? I will research it locally.
There was issue with the execution command. Earlier I was using testcafe chrome --autoplay-policy=no-user-gesture-required src/tests/.js -s takeOnFails=true. But now i have changed it to testcafe 'chrome --autoplay-policy=no-user-gesture-required' src/tests/.js -s takeOnFails=true and it worked.
I have a page that I'm able to get accessibility test report from Pa11y 5 using actions.
When I click on a button on that specific page, I get a popup/overlay, I would like Pa11y to sniff that popup/overlay page and report on accessibility metrics, but currently Pa11y 5 is only able to provide me for the main parent page ignoring any reports on the html in the popup page? Is there a way to achieve this, tell Pa11y to switch to popup and sniff on that popup html and report that.
Popup/overlay contains div[role='dialog'] as it is a modal dialog made out of aria.
I'm using the latest Pa11y, hence I keep mentioning it as Pa11y 5. I have not used Pa11y4, so cannot comment if this works with Pa11y 4.
Any help/advise is sincerely appreciated.
Update:
As requested, below is my complete (relevant) part of the code
const PageOptions1 = {
timeout: 30000,
userAgent: 'A11Y TESTS',
actions: [
'screen capture screenshots/001-DefaultView.png'
]
};
const PageOptions2 = {
timeout: 35000,
userAgent: 'A11Y TESTS',
rootElement: 'div[role="dialog"]',
actions: [
'click element button[data-automation-id="ccbutton"]',
'wait for element div[role="dialog"] to be added',
'screen capture screenshots/002-Popup.png',
'click element i.fa-close',
'screen capture screenshots/002-DefaultView.png'
]
};
async function runPa11y(navigateUrl) {
try {
const results = await Promise.all([
pa11y(navigateUrl, PageOptions1),
pa11y(navigateUrl, PageOptions2),
]);
LogResults(results);
} catch (error) {
console.error("Error: " + error.message);
}
}
runPa11y("Url to navigate");
Thanks for your updates! You're doing the right things and everything looks like it's working as expected.
Pa11y will perform all of the Actions before running your test, so it's opening the modal dialog, immediately closing it again, and then running the test without it.
Break PageOptions2 into smaller units so that your last Action is the state you want to test against, and everything should be ok.
I am getting an exception while trying to open a new link. I have written python script and I expected it will open new link whenever it meets certain condition but while it meet condition it shows alert popup(while entering my credential, it shows exception) and I don't know how to fix it. Currently I am working on Firefox browser and I also checked previous questions related to this issue, where their issue got fixed by changing the browser from Firefox to IE, but in my case I can't use IE since my base link will not open(support) in IE. Is there any way to fix this one?
Here is my code:
import time
from datetime import datetime
from selenium import webdriver
try:
driver = webdriver.Firefox(executable_path="C:\\Users\\Programs\\Python\\Python36\\Lib\\site-packages\\selenium\\webdriver\\firefox\\geckodriver.exe")
driver.get('https://base_link')
my_id = driver.find_element_by_name('j_username')
my_id.send_keys('1895')
password = driver.find_element_by_name('j_password')
password.send_keys('1895')
ext = driver.find_element_by_name('extension_login_user')
ext.send_keys('4081111895')
sign_in_button = driver.find_element_by_id('signin-button')
sign_in_button.click()
time.sleep(30)
driver.set_window_size(1024, 768)
driver.maximize_window()
ticket_opened = False
window = 0
while True:
if driver.find_element_by_id('state-text').text == 'Not Ready - GMC Work':
time.sleep(1)
if driver.find_element_by_id('state-text').text == "Not Ready - Break":
if ticket_opened is False:
driver.execute_script("$(window.open('child_link'))")
driver.switch_to_window(driver.window_handles[window])
window += 1
continue
else:
ticket_opened = False
else:
continue
else:
continue
except Exception as e:
print('Exception Occurred: ' + str(e))
print('Time and Date: ' + str(datetime.now())[0:19])
Here I am getting the exception (output):
Exception Occurred: Alert Text: None
Message:
Time and Date: 2017-10-19 04:13:39
Kindly help me to fix out this one using python selenium. If we can't fix this one, then kindly suggest me some other tool/way to fix this one.
I'm coding my Google Chrome Extension where I set the app's icon from the background script as such:
try
{
objIcon = {
"19": "images/icon19.png",
"38": "images/icon38.png"
};
chrome.browserAction.setIcon({
path: objIcon,
tabId: nTabID
});
}
catch(e)
{
}
Note that I wrapped the call in try/catch block.
Still, sometimes I'm getting the following message in the console log:
Unchecked runtime.lastError while running browserAction.setIcon: No
tab with id: 11618.
It's hard to debug this error because it seems to come up only when I close or reload the Chrome tab, it doesn't have a line number or any info for me to track, plus it's not easy to run through a debugger (i.e. I cannot set a break-point on the moment when error occurs, but if I blindly set a break-point on the chrome.browserAction.setIcon() line, I don't see the message in the log anymore.)
So I'm curious if anyone could suggest how to remedy this error?
EDIT: Just to post an update. I am still unable to resolve this issue. The suggestion proposed by #abraham below offers a somewhat working approach, but it is not fail safe. For instance, in a situation when the tab is closing I may call his suggested chrome.browserAction.setIcon() that may succeed if the tab is not yet closed, but while within its callback function the tab may eventually close and thus any consecutive calls to some other API that requires that same tab ID, say setBadgeBackgroundColor() may still give me that same No tab with id exception. In other words, for those who know native programming, this is a classic race condition situation. And I'm not sure if it's a bug in Chrome, because obviously JS does not offer any thread synchronization methods...
I've witnessed this behavior several times while doing my tests. It doesn't happen often because we're talking about very precise timing situation, but it does happen. So if anyone finds a solution, please post it below.
Include a callback and check chrome.runtime.lastError.
objIcon = {
"19": "images/icon19.png",
"38": "images/icon38.png"
};
function callback() {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError.message);
} else {
// Tab exists
}
}
chrome.browserAction.setIcon({
path: objIcon,
tabId: nTabID
}, callback);
The below works for me
/**
* Update icon, text and background
* Handle the case where the tab_id no longer exists
*/
function updateIconAndBadge(tab_id, icon_path, badge_text, badge_background_color) {
// Set the icon path
chrome.browserAction.setIcon({ path: icon_path, tabId: tab_id },
// Call back
() => {
// Check for error
if (chrome.runtime.lastError) {
// Failed - tab is gone
console.log(`Tab ${tab_id} no longer exists.`);
}
else {
// Ok - Set the badge text
chrome.browserAction.setBadgeText({
tabId: tab_id,
text: badge_text
});
// Set the back ground colour
chrome.browserAction.setBadgeBackgroundColor({
tabId: tab_id,
color: badge_background_color
});
}
});
}