Cypress and `device-width`
This is one of those issues where it's easier for Muhammed go to the mountain.
Websites tend to use min-width
for their media queries even though mostly min-device-width
is better. But testing device-width
with Cypress is quite the challenge.
In most cases people use either / or. So why not swap out min-device-width
for min-width
for the mobile tests to pass. Not in the compiled sources of course, in runtime: right before the test.
Cypress.Commands.add('swapDeviceWidth', () => {
cy.document().then(doc=>{
let replaced = 0
Array.from(doc.styleSheets).forEach(sheet => {
try {
Array.from(sheet.cssRules).forEach((rule:CSSRule, index) => {
const {cssText} = rule
const regexQuery = /(\(\s*)(min|max)-device-(width|height)(\s*:)/
const hasDeviceWidth = cssText.match(regexQuery)
if (hasDeviceWidth) {
const newRule = cssText.replace(regexQuery, '$1$2-$3$4')
sheet.removeRule(index)
sheet.insertRule(newRule, index)
replaced++
}
})
}catch(err){/* prevent InvalidAccessError on external sources*/}
})
cy.log(`Replaced ${replaced} -device- rules`)
})
})
It might not be the best solution but at least it works.