Open jennifer-shehane opened 9 years ago
When I issue a .click()
command, this should issue a .hover()
over the element I've specified to click onto (in order to fully simulate mouse behavior).
I don't think it's possible to implement a hover function with support for the css pseudo selectors considering it's a trusted event. http://www.w3.org/TR/DOM-Level-3-Events/#trusted-events The only way to simulate a hover to play css animations is by adding / removing a class.
A solution could be to modify and reinject the css to ensure that all :hover pseudo selectors are made available as a class.
Correct, it is not possible to trigger the CSS pseudo selectors via JavaScript directly, but it is possible to re-create what CSS does on a hover using just JavaScript (without the user changing anything).
When browsers run in cross browser mode we simply use the OS to actually hover over an element by its coordinates, so this isn't an issue in that mode.
However when testing in your local environment, Cypress has to simulate all events, and thats where the problem comes in.
I experimented with a few different solutions nearly a year ago, and found one to work really well. It works like this - on hover
find the element at the center of the coordinates, walk up the parent tree for every element we are currently hovering based on the CSS box model (not the DOM object model).
For each of those elements iterate through the css and figure out if a hover pseudo state applies. If it does, then inline that style directly on each element. This will achieve all CSS results in JavaScript.
However that's only half the battle.
The reason this command hasn't been finished is 2 reasons:
cy.click
- so this is no longer a barrier (but it used to be)mouseover
, mouseout
need to be simulated as well (which is easy at this point). But the biggest issue here is semantics. For instance, at what point does the user stop hovering over an element? Deciding when to fire the mouseout
is the real challenge.I originally imagined cy.hover
to actually be a callback function like this:
cy.get("button").hover(function(){
cy.get("span").click()
...
...
})
However that puts a lot of work on the user, and its possible you can create impossibilities. But the idea was that by using a callback function the user could specify the semantics of "continue hovering until X".
That is probably overkill though. Instead I will just dumb down the method and if edge cases occur handle them when they arise.
Hover additionally needs to be automatically invoked under the hood to properly simulate user action. For instance any click
should automatically first hover over the element, and I guess mouseout
when the action is done?
Anyway, that's why hover
hasn't been done yet. It was dependent on a lot of other commands to be figured out, although it is ready now to be solved.
I hope to be able to write assertions about pseudo-classes since this isn't readily accessible without the work outlined above by @brian-mann.
Example assertion
cy.get(“.content”).hover().should("have.attr", "style”, “cursor:alias”)
.hover()
should return element chained to hover with the element having applied the styles specified within :hover
pseudo-class.
This helped me out to at least show my element to be able to click it: https://docs.cypress.io/v1.0/docs/invoke#section-properties-that-are-functions-are-invoked
cy.get('.content').invoke('show').click();
Good point. We're going to add a pivotal story to write the documentation for cy.hover
which redirects you and provides examples how to easily solve this.
Using cy.hover() will now provide a detailed error message with a link for working around hover constraints in 0.15.0
.
The following workaround works for me:
Cypress.addChildCommand('triggerHover', function(elements) {
elements.each((index, element) => {
fireEvent(element, 'mouseover');
});
function fireEvent(element, event) {
if (element.fireEvent) {
element.fireEvent('on' + event);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(event, true, false);
element.dispatchEvent(evObj);
}
}
});
Which now allows me to:
cy
.get('.resultsHeading .icon-info-circle:first')
.triggerHover()
.get('.header-tooltips')
.should('exist')
HTH someone.
Yup, this simulates the event which is likely good enough in situations where you only have a simple javascript bound event handler.
To make this solution more complete we would need to:
clientX/Y
properties which tell where the event is originating on the page. We calculate these for other Cypress commands such as cy.click
which by default uses the exact center of the element, but this is configurable.cy.click
as well).:hover
styles on an element, which is likely what you're trying to do with hover
. The only way to get around this is to go outside of the Javascript sandbox and use browser drivers aka the debugger protocol to fire native events - or parse all of the applied :hover
rules and invoke them manually by inlining their styles on the element. Inlining styles will work but it has some edge cases. Creating a native event also has drawbacks (you can't have dev tools open, etc).My thoughts are we still attempt to workaround hover purely in Javascript by inlining styles, but provide a {native: true}
option which fires a native event. Once we do this, we can enable this option for all of the other commands too because.
I have on good authority been told that dev tools will eventually support multiplexed connections which means we'd no longer being booted off of the protocol whenever dev tools is opened by the user. This would make generating native events the preferred way in Cypress as opposed to event simulation.
Re the example above... for javascript hovers this works:
cy
.get('.resultsHeading .icon-info-circle:first')
//.triggerHover()
.then(function($heading) { $heading.trigger('hover'); })
.get('.header-tooltips')
.should('exist')
As per the above example - this will only work if you're using jquery
to bind the hover
event, since this is calling the trigger
method on the jquery element.
Also you can write what you wrote a bit more succinctly like this:
EDIT: read my comment here for an updated example using cy.trigger()
: https://github.com/cypress-io/cypress/issues/10#issuecomment-346436968
Lastly you can ditch the should('exist')
because that is the default assertion on all DOM commands.
https://docs.cypress.io/docs/finding-elements#section-existence
We've added a recipe which explains how to simulate hover / get around this.
I simulate the hover by dispatching the event 'mousemove',and it worked for me. the question I faced with is : the chart is painted by SVG based on the React framework, and the tooltip can be seen only when the mouse hover it .
my solution is
// create a event 'mousemove'
let e = new Event('mousemove', { bubbles: true, cancelable: true })
// give corresponding value to its target position
e.clientX=300;e.clientY=400
// dispatch the event
selector.dispatchEvent(e)
With cy.trigger()
you can do things like...
cy.get('button').trigger('mouseover') // or mouseenter based on what your app is bound to
@brian-mann I'm curious if you've seen any issues using .trigger('mouseover') with php/jqery elements? I am unable to make it work. It will go to the correct element but the element doesn't recognize it as a mouse hover.
Events all work the same way in Javascript. As long as you trigger the event that your element/plugin/whatever is bound to - it will fire.
It's possible your code is not bound to mouseover
, or that you'll need to provide additional properties on the event to make it work. It all completely depends on how your code is written.
@brian-mann I guess hoverIntent is what we are using: https://github.com/briancherne/jquery-hoverIntent. Have you encountered this at all? Any ideas would be appreciated if you know off the top of your head.
Regarding this issue we finally ran into a scenario in which we have a :hover
style that sets the display
and it can't be reproduced currently in JS. Rather than adding JS to handle the situation we just added a duplicate style for .cy-hover
and we addClass
that class in the cypress test itself via a custom command. This isn't something I'd want to get in the habit of, but it seems like a fairly unique scenario and this prevents the need for ad-hoc js hover solutions when a :hover
will do.
Understood. Any reason you couldn't just force the display of the element itself as opposed to modifying its CSS styles?
Something like: cy.get('button').invoke('show')
Hmm yeah in the cases where the :hover
is only affecting the display
or rather the only thing needed for the test that would cover it, but you'd lose any transitions or whatever else might be on the style
I tried different suggestions provided but still find it hard to simulate the correct stylings that should happen on all the elements with css :hover, which is a pain. If there are a lot of css :hover styles implemented, you'll see the application renders very differently from the actual visual. :(
in fact, seeing how puppeteer can support hovering with their hover i still think this should be possible as well for cypress. :/
I am trying to automate one hover event in an angular application. Below is the code..
div class="childAvaName boxSize auto_test_dp parentPart ui-listHeader ui-collapse-button ng-scope handClick" ng-class="{'handClick':(parent.children.length > 2)}" ng-include="family_dropdown_obj.parent_dropdown_path" ng-init="dropdown_mode = 'header'" ng-mouseleave="bigListShow(false)" ng-mouseover="bigListShow(true)"><div class="childAva img-circle bgFit ng-scope" id="auto_test_dp" ;);
I tried cy.get('.auto_test_dp').trigger('mouseover')
But after mouseover, the dropdown modal is not showed.
I had tried many options and none of them are working. can u suggest any other options instead of doing force:true
. ?
@maheswaranunni you just need to look at your application's code in response to the mouseover
event. It likely is doing some math on clientX
or clientY
properties. If that's the case you'll need to provide those.
The :hover
problem is interesting. How about iterating through
document.styleSheets
finding :hover
in .cssText
. If found make and attach a copy of it but switching :hover
for some arbitrary fake hover class e.g. .cypress-fake-hover
. Then add that class in js when testing.
Would it not be easy to just make a custom command that uses prevSubject
for an element than too just say subject.trigger('mouseover')
so the command would be cy.hover()
right after you get an element?
I'm not sure I follow, would that pseudo css :hover
effects?
I'm not sure I follow, would that pseudo css :hover effects?
Currently a way to hover is to use
cy.get('element')
.trigger('mouseover')
Would it not make sense to just use custom commands (Which can inherit a previous subject such as an element)
Use a child command that will simply use the previous element and do a .trigger('mouseover')
the :hover
problem hi-lighted earlier in the thread is about the inability to test states that only happen with css psuedo rules rather than javascript onHover
events which is what .trigger
does.
the :hover problem hi-lighted earlier in the thread is about the inability to test states that only happen with css psuedo rules rather than javascript onHover events which is what .trigger does.
The initial post did not say this...I've implemented the click function to do a hover action prior to clicking with selenium. I'm talking about eariler where this issue was closed and the solution was to do a .trigger('mouseover')
but instead make it a custom command.
I am using tippy.js to display tool tips. .trigger('mousehover') does not work. Please suggest a way
Hi guys! We have an AngularJS application and we are using cypress for E2E tests. However we got stuck in a problem with hovering over elements. In particular we have a side menu with some icons. Hovering on an icon will trigger the panel with side menu links. Writing the test with cypress we find out that hover is not simple as it looks. In particular for this menu we are using angular helpers like ng-mouseenter to trigger hover and add the class .open that will trigger the side panel with the side menu links. Debugging we found out that the system find the element but nothing can trigger the mouseover on it. Suggestions here https://docs.cypress.io/api/commands/hover.html#Workarounds weren’t effective. We already used the dispatchEvent method without any success. Any suggestions? Thanks in advance for your support.
The following workaround works for me:
Cypress.addChildCommand('triggerHover', function(elements) { elements.each((index, element) => { fireEvent(element, 'mouseover'); }); function fireEvent(element, event) { if (element.fireEvent) { element.fireEvent('on' + event); } else { var evObj = document.createEvent('Events'); evObj.initEvent(event, true, false); element.dispatchEvent(evObj); } } });
Which now allows me to:
cy .get('.resultsHeading .icon-info-circle:first') .triggerHover() .get('.header-tooltips') .should('exist')
HTH someone.
Is any of this actually functional in the latest version of Cypress? I'm using TS by the way, but things like "addChildCommand" and the fact that your function expects an element but your example shows you passing none seem quite wrong. Am I missing something or is this just outdated? If the latter is true can someone help me understand what changes are needed?
P.S. why is this issue still lingering after nearly 4 years of talking about it???
@DavidGWheeler Cypress.addChildCommand
was replaced with Cypress.Commands.add
.
We prioritize issues we work on based on a variety of factors - including the number of users requesting/helped by a feature. While this is still on our Roadmap, many other features are a higher priority today.
The .trigger('mouseover')
solutions don't cause CSS changes, so we are left without a workaround even for that use case.
Agree with @lukenofurther, the trigger workaround does not work. I can call click({ force: true })
, and click a button that isn't visible but I can't assert that my UI is showing the button when an element is hovered.
Given that this is a permission issue with trusted events, is the Firefox or Chome teams willing to help get this working through command line args like --untrustedEventsTrusted --Iknowitsaterribleidea.
@paulirish batsignal.jpg 📡
A potential cypress fix might be to make fake :hover's in the transform step, e.g. change div:hover { display: block }
to div:hover, div.cy-hover { display: block }
Would of course like a better solution. This is a big pain point in testing visual changes.
There is no way of triggering psuedo selectors with javascript. I think my idea of iterating CSS is the only way.
On Thu, 3 Oct 2019, 21:05 Tom Longson, notifications@github.com wrote:
A potential cypress fix might be to make fake :hover's in the transform step, e.g. change div:hover { display: block } to div:hover, div.cy-hover { display: block }
Would of course like a better solution. This is a big pain point in testing visual changes.
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/cypress-io/cypress/issues/10?email_source=notifications&email_token=AASM677J6P4MOME45FDWVMDQMZGCFA5CNFSM4A67JSKKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEAJNV7A#issuecomment-538106620, or mute the thread https://github.com/notifications/unsubscribe-auth/AASM674XICEATQUAWBL52PDQMZGCFANCNFSM4A67JSKA .
The following workaround works for me:
Cypress.addChildCommand('triggerHover', function(elements) { elements.each((index, element) => { fireEvent(element, 'mouseover'); }); function fireEvent(element, event) { if (element.fireEvent) { element.fireEvent('on' + event); } else { var evObj = document.createEvent('Events'); evObj.initEvent(event, true, false); element.dispatchEvent(evObj); } } });
Which now allows me to:
cy .get('.resultsHeading .icon-info-circle:first') .triggerHover() .get('.header-tooltips') .should('exist')
HTH someone.
Is any of this actually functional in the latest version of Cypress? I'm using TS by the way, but things like "addChildCommand" and the fact that your function expects an element but your example shows you passing none seem quite wrong. Am I missing something or is this just outdated? If the latter is true can someone help me understand what changes are needed?
P.S. why is this issue still lingering after nearly 4 years of talking about it???
Did you find a way to make the workaround work with TypeScript? I am having the same problem.
Haven't seen this mentioned anywhere, but the package Mr0grog/nightmare-real-mouse worked well for me when I was automating something that required hover action.
The implementation may be basic, but if it fulfills majority of the simple use cases, then it may be worth porting it over.
As mentioned above, puppetter does handle element hovering pretty well.
Digging onto the code to search how he's doing it, I found something who look like an elegant solution to avoid a lot of troubles who come from dealing with the DOM and CSS styles.
The hover function is defined like so:
async hover() {
await this._scrollIntoViewIfNeeded();
const {x, y} = await this._clickablePoint();
await this._page.mouse.move(x, y);
}
...
// _page.mouse.move
async move(x, y, options = {}) {
const {steps = 1} = options;
const fromX = this._x, fromY = this._y;
this._x = x;
this._y = y;
for (let i = 1; i <= steps; i++) {
await this._client.send('Input.dispatchMouseEvent', {
type: 'mouseMoved',
button: this._button,
x: fromX + (this._x - fromX) * (i / steps),
y: fromY + (this._y - fromY) * (i / steps),
modifiers: this._keyboard._modifiers
});
}
}
So, basically, puppeter leverage the Input.dispatchMouseEvent
from the devtools and simply move the mouse to the desired hover position. I've seen into cypress code that CDP's are already used into the browsers
section.
I am curious to know if this kind of implementation would look like a decent solution to the maintainers, also, I think this is related to #311 since this approach do trigger native events.
For those who are looking for a solution to trigger ":hover": Since cypress 3.8.0 you can run chrome in headless mode (there was an open issue that has been fixed and is available in the next release, see: https://github.com/cypress-io/cypress/issues/5949#issuecomment-567735351 )
So you can utilize the chrome remote debugger protocol. See this example: https://github.com/cypress-io/cypress-example-recipes/pull/384
For me this command does not work:
cy.get('button').trigger('mouseover') // yields 'button'
as a solution I have done:
cy.get('button').trigger('mouseenter')
and then
cy.get('button').trigger('mouseleave')
@ericjorgeamaral , @jennifer-shehane and all, Here is an example :
And my button source code :
<button class="root-0-1-21 secondary-0-1-28" id="defaultBtn">Default</button>
I want to test my color button during the "hover" state and screenshot this state. If i use it :
cy.get('#defaultBtn').trigger('mouseenter').matchImageSnapshot();
or
cy.get('#defaultBtn').trigger('mouseleave').matchImageSnapshot();
or
cy.get('#defaultBtn').trigger('mouseover').matchImageSnapshot();
For me, it's unable to keep the hover state for checking the background color.
Desired behaviour : When i use my script previously
Do you have any workaround ?
-- Env -- Cypress 3.8.1 Chromium 81
I am using tippy.js to display tool tips. .trigger('mousehover') does not work. Please suggest a way
It's not mousehover, it's mouseover.
@emirhangl mousehover
is not a DOM mouse event. Try mouseover
or mouseenter
and their counterparts, mouseout
and mouseleave
respectively.
Any update on this issue? we started using cypress for our company automated testing. we working with charts and mouse over function very critical for us.
This issue is still in the 'proposal' stage, which means no work has been done on this issue as of today, so we do not have an estimate on when this will be delivered.
Please refrain from commenting asking for updates 🙏
Our team will comment on this issue when there are any further updates.
Need to be able to hover in/out of DOM elements.
Example for hover
I'm not sure what a stop hover command would look like.
Currently I would achieve this with
mouseOver
andmouseOut
events. The hover command could follow a similar convention.Other considerations: