Cannot locate by CssSelector in Selenium WebDriver - selenium

I use the :contains() method but I get the error below:
Test Name: TheMahler3Test
Test FullName: TestingCssSelector.Mahler3.TheMahler3Test
Test Source: c:\Users\amahallati\Desktop\TestContainsSelector\TestingCssSelector\Mahler3.cs : line 50
Test Outcome: Failed
Test Duration: 0:00:05.135
Result Message: System.InvalidOperationException : An invalid or illegal string was specified
Result StackTrace:
at OpenQA.Selenium.Support.UI.DefaultWait1.PropagateExceptionIfNotIgnored(Exception e)
at OpenQA.Selenium.Support.UI.DefaultWait1.Until[TResult](Func`2 condition)
at TestingCssSelector.Mahler3.TheMahler3Test() in c:\Users\amahallati\Desktop\TestContainsSelector\TestingCssSelector\Mahler3.cs:line 59
This is the page's source code:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<div id="myDiv">
<select name="mySelectInput">
<option value="">Select one...</option>
<option value="1">AT&T</option>
<option value="2">TMobile</option>
</select>
</div>
</div>
</body>
</html>
And this is the WebDriver C# code:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Interactions;
namespace TestingCssSelector
{
[TestFixture]
public class Mahler3
{
private IWebDriver driver;
private StringBuilder verificationErrors;
private string baseURL;
private bool acceptNextAlert = true;
[SetUp]
public void SetupTest()
{
driver = new FirefoxDriver();
baseURL = "http://localhost:49638/";
verificationErrors = new StringBuilder();
}
[TearDown]
public void TeardownTest()
{
try
{
driver.Quit();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual("", verificationErrors.ToString());
}
[Test]
public void TheMahler3Test()
{
driver.Navigate().GoToUrl(baseURL + "/");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(40));
wait.Until(d =>
{
return driver.FindElement(By.XPath("/html/body/div/div/select"));
});
driver.FindElement(By.XPath("/html/body/div/div/select")).Click();
wait.Until(d =>
{
return driver.FindElement(By.CssSelector("option:contains('AT&T')"));
});
driver.FindElement(By.CssSelector("option:contains('AT&T')")).Click();
// ERROR: Caught exception [ReferenceError: selectLocator is not defined]
}
private bool IsElementPresent(By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
private bool IsAlertPresent()
{
try
{
driver.SwitchTo().Alert();
return true;
}
catch (NoAlertPresentException)
{
return false;
}
}
private string CloseAlertAndGetItsText()
{
try
{
IAlert alert = driver.SwitchTo().Alert();
string alertText = alert.Text;
if (acceptNextAlert)
{
alert.Accept();
}
else
{
alert.Dismiss();
}
return alertText;
}
finally
{
acceptNextAlert = true;
}
}
}
}

contains is not part of the CSS selector specification and is therefore not going to work.
The contains selector we all know and love comes from Sizzle, the CSS-selector engine behind jQuery. Unless you wish to physically load Sizzle or jQuery into your page, then you are not going to be able to use your current solution.
The only real way of doing text-based searching is using XPath, or find a list of elements (using anyway you like) and filtering them within code.
For your basic page, it's easy enough to simply select it by ID, so simply:
Select select = new Select(driver.FindElement(By.Id("mySelectInput")));
You would then select it by using:
select.SelectByVisibleText("AT&T");

Related

How can I transfer a model to a Razor Component in Blazor server-side?

I am using Blazor server-side to make a chat room.
For the style of receiving the message and sending the message is different, I made a model named MsgModel
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlazorApp1
{
public class MsgModel: ComponentBase
{
public string MsgText { get; set; }
}
}
The razor components ReceiveMsg.razor and the SendMsg.razor are base on this model.
#inherits MsgModel
<h3>ReceiveMsg</h3>#MsgText
#inherits MsgModel
<h3>SendMsg</h3>#MsgText
In the index.razor, I wanna input the message text and display it immediately.
#page "/"
#foreach (MsgModel _MsgModel in MsgList)
{
if (_MsgModel.GetType() == typeof(ReceiveMsg))
{
<ReceiveMsg></ReceiveMsg>
}
else
{
<SendMsg></SendMsg>
}
}
<div id="inputDiv">
<EditForm Model="_InputMsgModel" OnValidSubmit="#SubmitText">
<InputText #bind-Value="_InputMsgModel.MsgText" />
</EditForm>
</div>
#code{
protected MsgModel _InputMsgModel { get; set; } = new MsgModel();
protected List<MsgModel> MsgList { get; set; } = new List<MsgModel>();
protected void SubmitText()
{
SendMsg _SendMsg = new SendMsg();
_SendMsg.MsgText = _InputMsgModel.MsgText;
MsgList.Add(_SendMsg);
}
}
Now the problem is: in the for block, I should transfer the _MsgModel to the component. Meanwhile, I don't know how to transfer it yet.
Would you please help me? Thank you.
Finally, I found a strange and stupid way to solve this.
I add these code into the MsgModel:
[Parameter]
public MsgModel TransferModel
{
set
{
CopyAll(value, this);
}
}
private void CopyAll<T>(T source, T target)
{
var type = typeof(T);
foreach (var sourceProperty in type.GetProperties())
{
if (sourceProperty.Name != "TransferModel")
{
var targetProperty = type.GetProperty(sourceProperty.Name);
targetProperty.SetValue(target, sourceProperty.GetValue(source, null), null);
}
}
}
And change the for block like this:
#foreach (Models.MsgModel _MsgModel in MsgList)
{
if (_MsgModel.GetType() == typeof(ReceiveMsg))
{
<ReceiveMsg ShowFullImage="#ShowFullImage" TransferModel="_MsgModel"></ReceiveMsg>
}
else
{
<SendMsg ShowFullImage="#ShowFullImage" TransferModel="_MsgModel"></SendMsg>
}
}
What a stupid way it is!

Multiple browser instance launch when i execute my test

I an new in specflow i am implementing framework. When i create one feature file with multiple scenario and execute my test than it open one browser instance and run successful when i add one more feature file with multiple scenario and execute my test than it launch multiple browser instance one instance for each scenario can anyone help me out what's wrong in my code
Start.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TechTalk.SpecFlow;
namespace Orange_HRM
{
class Start : SeleniumDriver
{
[BeforeScenarioBlock]
public void Setup()
{
Intitialize();
WebDriver.Navigate().GoToUrl(BaseAddress);
}
[AfterScenarioBlock]
public void TearDown()
{
Close();
}
}
}
SeleniumDriver.cs
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Orange_HRM
{
class SeleniumDriver
{
public static IWebDriver WebDriver;
public static string BaseAddress
{
get { return Constants.Url; }
}
public static void Intitialize()
{
WebDriver = new ChromeDriver();
WebDriver.Manage().Window.Maximize();
TurnOnWait();
}
public static void Navigate()
{
WebDriver.Navigate().GoToUrl(BaseAddress);
}
public static void Close()
{
WebDriver.Close();
}
public static void Quit()
{
WebDriver.Quit();
}
private static void TurnOnWait()
{
WebDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
WebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromMinutes(2);
}
}
}
You are using SpecFlow of techtalk.
Concept name is Hooks.
to perform automatic logic operations at specific timings.So, hooks are event bindings.
running tests in multiple threads with SpecFlow+ Runner.
So, you can put orders,
class Start : SeleniumDriver
{
[BeforeScenario(Order = 0)]
public void Setup()
{
Intitialize();
WebDriver.Navigate().GoToUrl(BaseAddress);
}
[BeforeScenario(Order = 1)]
public void TearDown()
{
Close();
}
}
i like to suggest you dont use them, Bindings Class without Hooks.
i.e. [BeforeTestRun] [AfterTestRun] use them instead.
[AfterScenario]
public void CleanUp()
{
if (seleniumDriver != null)
{
SeleniumDriver.Dispose();
seleniumDriver = null;
}
}
You can initialise and close the driver at Test Run level instead of scenario level. And maintain the url navigation alone at Scenario level. So that the driver will be initiated before test starts and quit after the test completes. Also the page will get refreshed before each scenario run.
namespace Orange_HRM
{
class Start : SeleniumDriver
{
[BeforeTestRun]
public static void Setup()
{
Intitialize();
}
[AfterTestRun]
public static void TearDown()
{
Quit();
}
[AfterScenarioBlock]
public void navigateToUrl()
{
WebDriver.Navigate().GoToUrl(BaseAddress);
}
}
}
Also you have used WebDriver.Close() instead WebDriver.Quit(). If we use WebDriver.Close() for the main window, then session will be terminated. Then if we try to access the same webdriver object again, it will throw No such session error.
WebDriver.Close() is meant for closing child window if we are working with mulitple windows. So to close main window, we have to use WebDriver.Quit() directly.

Selenium is unable to detect the Checkout button and add product in cart

The problem is, Selenium is unable to detect the Checkout button and add product in cart.
package automationFramework;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Checkout {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://sng.bestpricewebsitedesign.com/";
driver.manage().timeouts().implicitlyWait(90, TimeUnit.SECONDS);
}
#Test
public void testNewCheckout() throws Exception {
driver.get(baseUrl + "/index.php?route=common/home");
driver.findElement(By.linkText("Home")).click();
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.id("input-email")).clear();
driver.findElement(By.id("input-email")).sendKeys("leo#abc.com");
driver.findElement(By.id("input-password")).clear();
driver.findElement(By.id("input-password")).sendKeys("asdfgh");
driver.findElement(By.cssSelector("input.btn.btn-primary")).click();
driver.findElement(By.linkText("Store")).click();
driver.findElement(By.xpath("(//button[#type='button'])[14]")).click();
driver.findElement(By.cssSelector("#cart > button.dropdown-toggle")).click();
driver.findElement(By.id("button-payment-address")).click();
driver.findElement(By.id("button-shipping-address")).click();
driver.findElement(By.id("button-shipping-method")).click();
driver.findElement(By.name("agree")).click();
driver.findElement(By.id("button-payment-method")).click();
driver.findElement(By.id("button-confirm")).click();
driver.findElement(By.linkText("Continue")).click();
driver.findElement(By.linkText("Logout")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
Following is the code for adding 'Blue Tshirt' in cart and perform check out.
#Test
public void testNewCheckout() throws Exception {
driver.get(baseUrl + "/index.php?route=common/home");
driver.findElement(By.linkText("Home")).click();
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.id("input-email")).clear();
driver.findElement(By.id("input-email")).sendKeys("leo#abc.com");
driver.findElement(By.id("input-password")).clear();
driver.findElement(By.id("input-password")).sendKeys("asdfgh");
//driver.findElement(By.cssSelector("input.btn.btn-primary")).click();
driver.findElement(By.xpath("//input[#value='Login']")).click();;
driver.findElement(By.linkText("Store")).click();
driver.findElement(By.xpath("//h4/a[text()='Blue Tshirt']/following::span[text()='Add to Cart'][1]")).click();
//driver.findElement(By.cssSelector("#cart > button.dropdown-toggle")).click();
driver.findElement(By.xpath("//div[#id='cart']/button[1]")).click();
driver.findElement(By.id("button-payment-address")).click();
driver.findElement(By.id("button-shipping-address")).click();
driver.findElement(By.id("button-shipping-method")).click();
driver.findElement(By.name("agree")).click();
driver.findElement(By.id("button-payment-method")).click();
driver.findElement(By.id("button-confirm")).click();
driver.findElement(By.linkText("Continue")).click();
driver.findElement(By.linkText("Logout")).click();
}
I have tested above code and it works fine for me. Please replace the existing test method with above one and let me know, if it works for you.

Auto insertion of values in pop up text fields using selenium

I am trying to do auto-insertion of values to the fields inside the pop up(see attached image) using the code below. But the insertion of values to the fields is not happening using the automation code below.
Would appreciate, if someone can provide the reason and solution for the same.
Any help is appreciated:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.fail;
public class test9 {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private WebElement foundElement;
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.url.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void test9() throws Exception {
driver.get(baseUrl + "/Login.aspx");
driver.findElement(By.id("dnn_ctr362_Login_Login_DNN_txtUsername")).clear();
driver.findElement(By.id("dnn_ctr362_Login_Login_DNN_txtUsername")).sendKeys("comp-da#comp.com");//dummy username
driver.findElement(By.id("dnn_ctr362_Login_Login_DNN_txtPassword")).clear();
driver.findElement(By.id("dnn_ctr362_Login_Login_DNN_txtPassword")).sendKeys("password");//dummy password
driver.findElement(By.id("dnn_ctr362_Login_Login_DNN_cmdLogin")).click();
driver.findElement(By.xpath("//div[#id='Nav']/span/span/div[3]/a")).click();
driver.findElement(By.id("dnn_cd_Banner_Customer_b")).click();
Thread.sleep(10000);
WebElement userName = find(By.xpath("//*[#id=\"dnn_ctr384_View_CreateDealerAdmin_email\"]"),"abc#gmail.com");
find(By.id("dnn_ctr384_View_CreateDealerAdmin_firstname"),"Abc");
find(By.id("dnn_ctr384_View_CreateDealerAdmin_lastname"),"R");
find(By.id("dnn_ctr384_View_CreateDealerAdmin_firstname"),"test1");
find(By.id("dnn_ctr384_View_CreateDealerAdmin_lastname"),"abc");
find(By.id("dnn_ctr384_View_CreateDealerAdmin_password"),"password");
find(By.id("dnn_ctr384_View_CreateDealerAdmin_passwordconfirm"),"password");
search(By.id("dnn_ctr384_View_CreateDealerAdmin_create_b_input"));
driver.findElement(By.cssSelector("div.Controls")).click();
driver.findElement(By.id("dnn_dnnLogin_enhancedLoginLink")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public WebElement find(By by,String keys){
By byy = by;
String key=keys;
System.out.println(by.toString()+keys.toString());
for (int milis=0; milis<3000; milis=milis+3000) {
try {
foundElement = driver.findElement(by);
//driver.findElement(by).clear();
driver.findElement(by).click();
Thread.sleep(5000);
foundElement.sendKeys("");
Thread.sleep(5000);
foundElement.sendKeys(keys);
Thread.sleep(5000);
foundElement.sendKeys(keys);
} catch (Exception e) {
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
return foundElement;
}
public WebElement search(By by){
By byy = by;
for (int milis=0; milis<3000; milis=milis+3000) {
try {
driver.findElement(by).click();
driver.findElement(by).click();
} catch (Exception e) {
try {
Thread.sleep(200);
} catch (InterruptedException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
return foundElement;
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}
EDIT
Including the html which contains Email, First Name, Last Name etc.
<div id="Heading">
<span id="dnn_ctr384_View_CreateDA">Create DA</span>
<span class="nyk_ButtonSpan">
</div>
<table id="dnn_ctr384_View_CreateDealerAdmin" class="nykTable" border="0">
<tbody>
<tr class="nykRow">
<td class="nykCreateLbl" style="vertical-align: top">
<td class="nykCreateEntry">
</tr>
<tr class="nykRow">
<tr class="nykRow">
<tr class="nykRow">
<tr class="nykRow">
<tr id="dnn_ctr384_View_CreateDealerAdmin_assigned2_row" class="nykRow">
<tr class="nykRow">
</tbody>
</table>
Instead of using "Alert alert = driver.switchTo().alert()" statement you will have to use "driver.switchTo().activeElement()".This is the solution of your problem.

Screen resolution test

Does anyone know a desktop app for testing websites in different screen resolutions? The reason I am looking for a desktop app is because I want to be able to test websites that have internal URLs [of course I want to test in resolutions that are not available on my computer).
Thanks
I had similar problem. You can write JUnit and Selenium test app for that. It's not big deal, simply change screen resolution of driver object and take print screen automaticly. Image files are store in your project so you can see after test all resolutions of your site. Here is code for that :
public class TestCase1 {
/**
*
*/
private WebDriver driver;
private String url;
public TestCase1() {
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
// array of test urls
this.url = "http://www.google.com/";
// ChromeDriver
//System.setProperty("webdriver.chrome.driver", PATH_TO_CHROMEDRIVER);
//driver = new ChromeDriver();
driver = new FirefoxDriver();
driver.get(this.url);
}
#After
public void tearDown() {
driver.quit();
}
#Test
public void testResolution() {
driver.navigate().to(this.url);
String[] resulutions = {
"1366x768",
"1920x1080"
// add resolution
};
for (String resulution : resulutions) {
String[] parts = resulution.split("x");
// Screen resolution
Dimension screenRes = new Dimension(Integer.parseInt(parts[0]),Integer.parseInt(parts[1]));
// Set browser resolution
driver.manage().window().setSize(screenRes);
// little pause
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
//Logger.getLogger(TestClass.class.getName()).log(Level.SEVERE, null, ex);
}
driver.navigate().refresh();
// little pause
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
//Logger.getLogger(TestClass.class.getName()).log(Level.SEVERE, null, ex);
}
this.takeScreenShot(resulution);
}
}
/**
*
* #param fileName
*/
private void takeScreenShot(String fileName) {
File screenShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenShot, new File(fileName + ".png"));
} catch (IOException ioe) {
throw new RuntimeException(ioe.getMessage(), ioe);
}
}
}
Here is link for setting test project, importing selenium and other staff that you need to do that.