Comments (71)
It is possible to run a native system hover event using CDP. Find the ready-to-use hover command in this package https://github.com/dmtrKovalenko/cypress-real-events. Checkcy.realHover
command.
from cypress.
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).
from cypress.
Just sharing a workaround that worked for my project, using the right click. I hope this can help some of you.
cy.get('button').rightclick()
from cypress.
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();
from cypress.
The .trigger('mouseover')
solutions don't cause CSS changes, so we are left without a workaround even for that use case.
from cypress.
We've added a recipe which explains how to simulate hover / get around this.
from cypress.
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 do not comment asking for updates
Please refrain from commenting asking for updates 🙏
- It creates noise for other people watching progress here.
- It takes the team's focus away from current work.
Our team will comment on this issue when there are any further updates.
from cypress.
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.
from cypress.
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.
from cypress.
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:
- Fill in the missing event coordinates such as
clientX/Y
properties which tell where the event is originating on the page. We calculate these for other Cypress commands such ascy.click
which by default uses the exact center of the element, but this is configurable. - Replicate handling the CSS object model - meaning the event should actually originate at the topmost element (which is how we handle
cy.click
as well). - Still the hardest thing about hover is that you cannot invoke CSS pseudo properties from Javascript. There is no way to trigger the
:hover
styles on an element, which is likely what you're trying to do withhover
. 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.
from cypress.
With cy.trigger()
you can do things like...
cy.get('button').trigger('mouseover') // or mouseenter based on what your app is bound to
from cypress.
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')
from cypress.
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.
from cypress.
Three workarounds if .invoke('show')
and .trigger('mouseover')
doesn't work because of css :hover.
.trigger('mouseenter');
.rightclick();
.nhover();
from here: https://github.com/avallete/cypress-nhover thanks to @avallete
from cypress.
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)
from cypress.
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???
from cypress.
@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.
from cypress.
@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
from cypress.
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.
from cypress.
in fact, seeing how puppeteer can support hovering with their hover i still think this should be possible as well for cypress. :/
from cypress.
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')
from cypress.
If you are a Bulma user then this works in lieu of the CSS :hover
implementation:
cy.get("#my-dropdown").within(() => {
cy.get(".is-hoverable").invoke("addClass", "is-active");
});
from cypress.
I am using tippy.js to display tool tips. .trigger('mousehover') does not work.
Please suggest a way
from cypress.
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.
from cypress.
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: #5949 (comment) )
So you can utilize the chrome remote debugger protocol. See this example: cypress-io/cypress-example-recipes#384
from cypress.
Just sharing a workaround that worked for my project, using the right click. I hope this can help some of you.
cy.get('button').rightclick()
from cypress.
@silversonicaxel I think this is impossible
from cypress.
https://github.com/dmtrKovalenko/cypress-real-events. works nicely!
Very nice! I hope this gets implemented for FF as well, but for now, this is excellent!
I confirm this, I'm using Cypress for job and I have to replicate an hover on a menu.
I spent almost 3 hours, nothing worked but this, using cy.get(<element>).realHover()
.
Have a try, no big installs, just yarn add cypress-real-events --dev
, add a line in cypress/support/index.js
and use it.
from cypress.
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.
from cypress.
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.
from cypress.
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.
from cypress.
https://github.com/dmtrKovalenko/cypress-real-events. works nicely!
from cypress.
https://github.com/dmtrKovalenko/cypress-real-events. works nicely!
Very nice! I hope this gets implemented for FF as well, but for now, this is excellent!
from cypress.
You can use cypress-real-events to test css as well.
from cypress.
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.
from cypress.
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()
: #10 (comment)
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
from cypress.
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.
from cypress.
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:
- Figuring out the parents by the CSS box model and not the DOM took awhile to get right - but now it is correct and it's already been implemented by
cy.click
- so this is no longer a barrier (but it used to be) - There are other things that go with a "hover" besides just CSS styles. For instance:
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 themouseout
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.
from cypress.
Using cy.hover() will now provide a detailed error message with a link for working around hover constraints in 0.15.0
.
from cypress.
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')
from cypress.
@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.
from cypress.
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.
from cypress.
@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.
from cypress.
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.
from cypress.
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')
from cypress.
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
from cypress.
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. :(
from 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
. ?
from cypress.
@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.
from cypress.
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.
from cypress.
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?
from cypress.
I'm not sure I follow, would that pseudo css :hover
effects?
from cypress.
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.
from cypress.
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 📡
from cypress.
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.
from cypress.
from cypress.
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.
from cypress.
@emirhangl mousehover
is not a DOM mouse event. Try mouseover
or mouseenter
and their counterparts, mouseout
and mouseleave
respectively.
from cypress.
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.
from cypress.
Please use: #10 (comment)
from cypress.
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-invokedcy.get('.content').invoke('show').click();
worked like a charm, thanks!
from cypress.
I have an application that is made of web components with lit-html. I could not make hover to work with the help of invoke or trigger along with experimental shadow dom as true. Any suggestions?
from cypress.
It is possible to run a native system hover event using CDP. Find the ready-to-use hover command in this package dmtrKovalenko/cypress-real-events. Check
cy.realHover
command.
This worked like a charm 🤗
from cypress.
Awesome
from cypress.
It is possible to run a native system hover event using CDP. Find the ready-to-use hover command in this package https://github.com/dmtrKovalenko/cypress-real-events. Check
cy.realHover
command.
This is really cool. Unfortunately, I'm looking for a solution that works for Chrome and Firefox :(
from cypress.
@vegerot can't you just target these onHover tests just on Chrome?
from cypress.
@silversonicaxel only if I didn't care about verifying my app on Firefox :p
from cypress.
Makes totally sense... I've a question by the way @vegerot
Are you maybe able to take snapshots of this realHover
event?
I am trying to use Applitools combined with Cypress and this extra plugin, but I can't catch the mouse over state on a snapshot.
Thanks
from cypress.
I haven't tried it, sorry
from cypress.
from cypress.
Three workarounds if
.invoke('show')
and.trigger('mouseover')
doesn't work because of css :hover.1. `.trigger('mouseenter');` 2. `.rightclick();` 3. `.nhover();` from here: https://github.com/avallete/cypress-nhover thanks to @avallete
I couldn't make it work.
from cypress.
Related Issues (20)
- Screenshot fails to reflect viewable 3D image in canvas element HOT 4
- Support React 19 in Component Testing
- Cypress can not type (cy.get(el).type) space char (' ') into input[type=email] ! HOT 1
- Flaky internal service-worker test on Firefox browser HOT 1
- Opt out of 'unload' event deprecation
- Add time and completion status when running all specs
- split windows job dependency from linux-x64 workflow
- Not able to uninstall Cypress 13.8.1 HOT 5
- Overwrite .type() command with promise times out
- Cypress CT + Angular can't resolve assets from stylesheets HOT 1
- Flaky tests: Launchpad: Setup Project (project-setup.cy.ts)
- Click on submit form does not recognize HTTP 302 response code
- Warning: EGL_EXT_create_context_robustness must be supported shown when running Cypress 13.8.1 HOT 2
- Cypress v13.9.0 is not running tests HOT 3
- CT: cypress doesn't recognize "+" symbol in the path to the Angular component HOT 3
- Cypress only runs the first test in the test suite and does not proceed further HOT 4
- Cypress, pnpm and OSX ARM64 gives
- cy.session failure that didn't come from my code HOT 2
- Cypress TestRail Simple plugin always return TypeError: Cannot read properties of undefined (reading 'length') HOT 1
- Enhance typings for cy.intercept and cy.wait
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from cypress.