Reputation: 21
I want to add a hover class using the Cypress testing framework. What commands or assertions should I use?
Upvotes: 1
Views: 5696
Reputation: 2460
I suggest that you add
.invoke('addClass', 'overDue')
To your cypress test in order to add a class
Upvotes: 5
Reputation: 103
This is a small simple "hackaround" the lack of hover support in cypress. I use focus() along with :focus, :hover { // ... } in my css. For the projects I work on, we usually match the focus style to hover, so if you do, then you can use this hack.
Assuming your CSS has this type of structure:
<style>
a {
color: red;
}
a:hover,
a:focus {
color: blue;
}
</style>
You can use cy.get($elm).focus() then test the attributes. Below is a full example from a working test.
cy.get('a.navigation__link')
.not('a.navigation__link--active')
.each($el => {
cy.wrap($el).should('have.css', 'color', 'rgb(0, 0, 0)')
cy.wrap($el).focus().should('have.css', 'color', 'rgb(211, 50, 57)')
})
Not trying to lead anyone down the wrong road here, this is just a workaround that can help you achieve the same visual result as hover, however its not an exact hover test.
Upvotes: 0
Reputation: 967
Testing css pseudo-classes like :hover can be tricky with Cypress and I'm not sure modifying classes is a good way to go. However, this can certainly be achieved with Puppeteer's page.hover() method.
You could create a cypress task under your plugins/index.js that launches Puppeteer (in case you want to control the tests from within Cypress), and return whatever values you need to confirm that your application behaves in an expected way.
const puppeteer = require('puppeteer');
//...
on('task', {
async launchPuppeteer(param1, param2){
const browser = await puppeteer.launch()
const page = await browser.newPage();
//do something
await page.hover(someElementThatReactsToHover)
//do other stuff
return valuesForCypress
}
})
And then in your .spec file you could call this task as follows:
cy.task('launchPuppeteer', {param1: 'whatever1', param2: 'whatever2'})
.then(valuesForCypress => cy.wrap(valuesForCypress).should('eq', expectedValues))
Upvotes: 0