selenide / selenide Goto Github PK
View Code? Open in Web Editor NEWConcise UI Tests with Java!
Home Page: http://selenide.org
License: MIT License
Concise UI Tests with Java!
Home Page: http://selenide.org
License: MIT License
Currently Selenium API doesn't provide method to find element by text. But we believe that Acceptance Tests must use visible text where possible. So, we should add several selectors:
For example, clicking the button will change it's class from 'btn btn-primary btn-save' to 'btn btn-save'.
I'm storing the button as SelenideElement to make checks later:
SelenideElement bSave = $(".btn-primary.btn-save");
Now, following code
SelenideElement bSave = $(".btn-primary.btn-save");
System.out.println(bSave.getLocation());
bSave.click();
System.out.println(bSave.getLocation());
Thread.sleep(5000);
System.out.println(bSave.getLocation());
will return
(1373, 365)
(1373, 365)
(1373, 549)
So "bSave" appears to be another button now. And the final check will fail:
bSave.should(hasNotClass("btn-primary"));
PS: I was able to write the same without using $() in pure Selenium and WebElement and it worked.
This method should wait until all options are loaded into the selectbox.
@Override
public String actualValue(WebElement element) {
return element.getCssValue(propName);
}
@Override
public String toString(){
return String.format("'%s' css property of '%s' value", propName, propValue);
}
};
I am not sure if it should be default or configurable behavior.
Code sample:
ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
driver = new ChromeDriver(options);
Create a'la "TestWatcher" that could take screenshots of failed tests.
Make error messages easily readable
Error message should clearly indicate that timeout is too short.
It's treated as a bad practice:
http://jimevansmusic.blogspot.com/2012/08/youre-doing-it-wrong-protected-mode-and.html
Selenide has method scrollTo, but it uses jQuery plugin "scroll".
The same effect could be achieved without using jQuery:
public static void scrollTo(WebElement element) {
int elementPosition = element.getLocation().getY();
String js = String.format("window.scrollTo(0, %s)", elementPosition);
JavascriptExecutor jsx = (JavascriptExecutor) getWebDriver();
jsx.executeScript(js, "");
}
Method driver.close() closes the window, but leaves IE or CHROME process alive.
https://github.com/codeborne/selenide/wiki/Snippets
For example:
waitUntil("#username", hasText("Hello, Johny!"), 8000);
Not sure we really need it, but why not.
If somebody wants to use PageObject, we could allow it by using
"return org.openqa.selenium.support.PageFactory.initElements(driver, MyPageObject.class)"
The API docs list ie, chrome, htmlunit, and firefox as valid browser values. Since WebDriver also supports phantomjs, are there plans to enable this in Selenide? HTMLUnit has so many problems as a headless browser that using Selenide in a headless environment is difficult/impossible.
Or maybe add only for IE?
Need to investigate why it is needed at all.
Like this:
$$().shouldHave(size(2), texts("A", "B"));
Having an element:
@FindBy(id = "invalid_id")
private WebElement categoryDropdown;
$(categoryDropdown).selectOption("SomeOption");
ElementNotFound {By.selector: option, in: NoSuchElementException: Unable to locate element: {"method":"id","selector":"invalid_id"}}
$(categoryDropdown).click()
produces the following error message: org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"invalid_id"}
EventFiringWebDriver efwd = new EventFiringWebDriver(webdriver);
efwd.register(new AbstractWebDriverEventListener(){...});
It is useful in case of any mysterious behavior.
For example, for line
$(languageDrpdwn).shouldHave(text("Java"))
it should write a log message Element <option>Javascript</option> contains text "Java"
.
-Dselenide.debug=true
@Test @Debug
public void myTest() {...}
both JUnit and TestNG could be supported
Different browsers treat spaces differently. For this row JohnMcClain some browsers think that text is "JohnMcClain", but others think that text is "John McClain".
It would be universal approach if text() condition would ignore whitespaces.
This is actual when options in selectbox are generated dynamically by javascript
Selenide closes the browser window when all tests are finished.
But it's often useful to leave browser window open during development.
Code:
$(".alert-success").shouldHave(text(message));
Result:
junit.framework.AssertionFailedError: {By.selector: .alert-success}
Expected: got text 'Deposit has been created. The amount will be transferred to it in a few moments. You can check the status of transfer in payment history.'
Timeout: 4 s.
Currently it's tuned for Struts2-like selectbox that contain elements.
Try to make it more generic.
For a test marked with @SoftAssert anntation:
If a test contains multiple asserts, it should check them all, and fail only after all checks.
This line of code:
$(By.xpath("##[id")).shouldNot(exist);
should throw exception that clearly says that XPath is invalid. Now Selenide just swallows this error.
Currently only IEDriver, FirefoxDriver, ChromeDriver and HtmlUnitDriver are supported.
Other drivers should be added:
what else?
Create a'la "TestWatcher" that could take screenshots of failed tests.
For RemoteWebDriver, screenshots should be taken differently from usual webdriver:
File scrFile;
if (driver.getClass().equals(RemoteWebDriver.class)) {
scrFile = ((TakesScreenshot) new Augmenter().augment(driver)).getScreenshotAs(OutputType.FILE);
} else {
scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
}
Now test results in the following exception:
org.openqa.selenium.InvalidElementStateException: Element is disabled and so may not be used for actions
Command duration or timeout: 15 milliseconds
Currently trying to execute open("www.yandex.ru");
causes quite unreadable error message:
org.openqa.selenium.WebDriverException: Component returned failure
code: 0x804b000a (NS_ERROR_MALFORMED_URI) [nsIIOService.newURI]
Command duration or timeout: 44 milliseconds
Build info: version: '2.31.0', revision:
'1bd294d185a80fa4206dfeab80ba773c04ac33c0', time: '2013-02-27
13:51:26'
System info: os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1',
java.version: '1.7.0_07'
Session ID: e697e9e5-1d3e-4f15-8855-196d02670da8
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=XP, databaseEnabled=true,
cssSelectorsEnabled=true, javascriptEnabled=true, acceptSslCerts=true,
handlesAlerts=true, browserName=firefox,
browserConnectionEnabled=true, nativeEvents=true,
webStorageEnabled=true, rotatable=false, locationContextEnabled=true,
applicationCacheEnabled=true, takesScreenshot=true, version=23.0.1}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
For example, this line: $("#progress tr", 3).find(byText("Edit")) returns FIRST, not the 3rd "Edit" button.
It would be convenient to declare one of "browser per test", "browser per class" strategy as an annotation to tests.
Now we have such an annotation only for JUnit. Need the same for TestNG.
The following test:
$(".validation-message[data-parameter-name='ssid']").shouldNotBe(visible);
Results in the following error message:
ElementMatches {By.selector: .validation-message[data-parameter-name='ssid']}
Expected: visible
Element: '<div class=validation-message>The WLAN name cannot contain special characters .</div>'
Timeout: 4 s.
It says: Expected: visible
, thought shouldNotBe(visible);
was requested.
It can be useful for running tests in multiple parallel threads (for example, TestNG allows it).
An example of TestNG configuration provided by Sergey Kuts:
<test name="IE 10 Test">
<parameter name="browser" value="internet explorer"/>
<parameter name="version" value="10"/>
<parameter name="platform" value="WINDOWS"/>
<classes>
<class name="class1">
<methods>
<include name = "method1"/>
<include name = "method2"/>
</methods>
</class>
</classes>
</test>
<test name="FF 10 Test">
<parameter name="browser" value="firefox"/>
<parameter name="version" value="10"/>
<parameter name="platform" value="WINDOWS"/>
<classes>
<class name="class1">
<methods>
<include name="method1" />
<include name="method2" />
</methods>
</class>
</classes>
</test>
Many events happen after few seconds (because of heavy usage of Ajax in modern web applications).
Currently it's possible to implicitly call waitUntil("#messages div", hasText("John")), but in most cases user does not even know about Ajax, so Selenide should wait automatically - as naturally as user does wait.
For example, method
$("#messages div").shouldHave(text("John")) should wait for few seconds until the "div" actually gets text "John" loaded.
assertURL()
Currently $$().shouldHave(texts("A", "B", "C"))
matches exact texts, but shuld match substrings.
By.xpath(".//*[contains(normalize-space(text()), "" + elementText + "")]")
По спецификации: http://www.w3.org/TR/xpath/#node-tests. text() - в действительности это не текст элемента, а функция, которая возвращает все текстовые ноды данного элемента. Т.е. в случае
Failing tests:
To check that all returned elements are visible
Some ElementsCollection methods (shouldHaveSize, shouldBe and shouldHave) do not support chaining, i.e. not possible to write such expressions:
$$("table tr").shouldHaveSize(10).filterBy(text("aaa"));
It would be nice if those can be chained the same way as other methods.
I assume that issue is caused by incorrect import statement in FilteringCollection.
java.lang.NoClassDefFoundError: com/beust/jcommander/internal/Lists
at com.codeborne.selenide.impl.FilteringCollection.getActualElements(FilteringCollection.java:21)
at com.codeborne.selenide.ElementsCollection.getActualElements(ElementsCollection.java:79)
at com.codeborne.selenide.ElementsCollection.size(ElementsCollection.java:104)
I have added jcommander to dependencies of my project as a temporary workaround.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.