if the element is displayed then the test failed - protractor

I need a way to make the test fail with specific message. For example if the element isDisplayed() i want the test to fail
element(myElement).isDisplayed().then(function(result) {
if (result) {
//test fail
}
else {
//do something else
}
}

You could use jasmine's done.fail:
it('your test', (done) => {
element(myElement).isDisplayed().then((result) => {
if (result) {
done.fail('a custom error message');
}
//do something else
});
});

You can simply pass the failure message as an extra parameter to jasmine matchers for every failure.Look at below example.
expect(element(myElement).isDisplayed()).toBe(true,'myElement is not displayed in the page.')
Here the message myElement is not displayed on the page. will be displayed in console/reporter if the above expect statement fails.

If you are using jasmine for reporting then you can override custom error message by implementing custom matchers for expect statements.
Note: we can directly pass custom error message as an additional parameter for in expect statements but that is not documented feature so may not be supported in future.It is better approach to implement it as custom matcher.

Related

PromiseKit, how to await a finalized promise?

coming from the JS world I'm having a bit of problem wrapping my head around promise kit flavor of promises, I need a bit of help with the following.
Assume I have a function that returns a promise, say an api call, on some super class I await for that promise, then do some other action (potentially another network call), on that parent call I also have a catch block in order to set some error flags for example, so in the end I have something close to this:
func apiCall() -> Promise<Void> {
return Promise { seal in
// some network code at some point:
seal.fulfill(())
}
}
// in another class/object
func doApiCall() -> ? { // catch forces to return PMKFinalizer
return apiCall()
.done {
// do something funky here
}
.catch {
print("Could not do first request"
}
}
now I'm trying to write some unit tests for this functionality, so the response is mocked and I know it will not fail, I just need to await so I can verify the internal state of my class:
// on my test file
doApiCall().done {
// test my code, but I get an error because I cannot pipe a promise that already has a `.catch`
}
How would one go about solving this problem? I could use finally to chain the PMKFinalizer but that feels wrong
Another tangential question would be, is it possible to re catch the error on a higher level, let's say a UI component so it can hold some temporary error state? as far as I see I did not see a way to achieve this.
Many thanks 🙏

onErrorResumeNext type inference failed

If my single errors because of a networkexception return Single.just(false)
If my single errors because of another reason return Single.error
If my single succeeds return the original Single value.
this should be as easy as
getStudent(studentId)
.onErrorResumeNext { if (it is NetworkException) return #onErrorResumeNext Single.just(true)
return Single.error(it) }
Type inference failed. Expected type mismatch SingleSource found Single
Your Single needs to return the same type as your source (I'm assuming getStudent() isn't returning a Boolean). If you want to represent a "success" and "error" states, Kotlin has a Result class just for this.
E.g.
getStudent()
.map { student ->
// Your logic here may look different
Result.success(student)
}
.onErrorResumeNext { error ->
if (error is NetworkException){
Single.just(Result.failure(error))
} else {
Single.error(error)
}
}
This will catch network errors and wrap the exception in a Result, all other exceptions will be propagated downstream. You can then choose how to handle the error in your subscribe method.
Depending on your use case however, you may want to also look into using Maybe or the retry() operator.

Screenshot on every failure using Scalatest

I would like to take a screenshot on every fail test in a Spec or Suite using ScalaTest.
The Scala Test website shows how to take screenshots surrounding every code that might fail with this:
withScreenshot {
drive.findElement(By.id("login")).getAttribute("value") should be ("Login")
}
There is this post that tries to explain, but I could not understand what exactly should be done.
I also found the class ScreenshotOnFailure.scala, but could not use it, once it's private and has a package restriction.
Can anyone tell me if there's a way to intercept any failure and then take a screenshot?
Just to have a final answer I'm writing the way I could solve the problem based on the approach from this post mentioned in the question.
In short, the solution ended up like this (pseudo-code).
trait Screenshots extends FunSpec {
...
override def withFixture(test: NoArgTest): Outcome = {
val outcome = test()
// If the test fails, it will hold an exception.
// You can get the message with outcome.asInstanceOf[Failure].exception
if (outcome.isExceptional) {
// Implement Selenium code to save the image using a random name
// Check: https://stackoverflow.com/questions/3422262/take-a-screenshot-with-selenium-webdriver
}
outcome
}
}
class MySpec extends Screenshots {
...
describe("Scenario A") {
describe("when this") {
it("the field must have value 'A'") {
// It will save a screenshot either if the selector is wrong or the assertion fails
driver.findElement(By.id("elementA")).getAttribute("value") should be ("A")
}
}
}
}
From this point on, all Specs that extend the Screenshot trait will intercept errors and save a screenshot.
Just to complement, surrounding areas with withScreenshot(), as mentioned in the question, saves only failure on assertions, but it does not save a screenshot when the test fails due an element not found (e.g. wrong selector).
With the code above, all failures will save a screenshot.

Play 2.3 - Changing to WebSocket.tryAccept from async

I'm new rather new to Scala so I think this might be a very small problem.
I'm currently trying to change the method chat from using the deprecated WebSocket.async to WebSocket.tryAccept. The application uses the sample chat found at PlayFramework websocket-chat
I'm having trouble creating the complex Future type that the method requires.
This is the old method:
def chat() = WebSocket.async[JsValue] {
request =>
ChatRoom.join("User: 1")
}
New method:
def chat2() = WebSocket.tryAccept[JsValue] {
request =>
try {
// ChatRoom.join returns (iteratee,enumerator)
ChatRoom.join("User: 1").map(e => Right(e))
} catch {
case e: Exception =>
Left(Ok("Failed")) // Error here
}
}
My error message:
found : Left[Result,Nothing]
required: Future[Either[Result,(Iteratee[JsValue, _], Enumerator[JsValue])]]
I have no idea how I am supposed to create such a complex result for such a simple message.
Although ChatRoom.join("User: 1").map(e => Right(e)) doesn't show any errors now, I'm unsure if this is the correct implementation.
I'm not in front of an IDE at the moment, so I can't answer fully, but the return type it's asking for isn't as complex as it seems. An "Either" is a "Left" or a "Right" in the same way that an "Option" is a "Some" or a "None". So what it's asking for is a Future (which Websocket.async should also have required) that contains either a Left[Result] -- the fail-to-connect case, or a Right[(Iteratee, Enumerator)] -- the success case. Assuming that Chatroom.join returns a Future[(Iteratee, Enumerator)], the map operation is simply wrapping that in a "Right". The first thing I'd try is wrapping Left(Ok("Failed")) in a Future and see what happens.

How to write your own matcher in Circumflex?

As asked here, I need to run a Circumflex action only if a condition is met. Currently, I do it like this:
get("/") = requireLogin {
...
}
Now Circumflex supports Matchers, which can be put right within the get() specification:
get("/mail" & Host("localhost"))
How can I write my own matcher, so the above requireLogin gets closer to the Circumflex style? I wish to write something like this:
get("/" & IsLoggedIn) = {
...
}
Here is a simple implementation. All it takes is to define an object with the desired name, extending from AtomicMatcher (as this one implements add() etc) and implement the name and apply methods:
object IsLoggedIn extends AtomicMatcher {
def name = "IsLoggedIn"
def apply = {
// Not shown: figuring out whether user is logged in or not
if(loggedIn) {
Some(List(new MatchResult(name)))
}
else {
sendRedirect("/login")
throw new ResponseSentException;
}
}
}
If the user is logged in (ie. the action can be executed), you need to return a list of at least one MatchResult. If you don't want to execute the action, do something else and either return None or throw a ResponseSentException, which seems to be the preferred way.