Created
March 3, 2022 09:06
-
-
Save iffa/c4f7ce8150a6b37c96972314ee7d6d99 to your computer and use it in GitHub Desktop.
Custom Cypress command for visiting a page with custom media matcher stubs & locale support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface MatcherOptions { | |
darkMode: boolean; | |
prefersReducedMotion?: boolean; | |
overrideLocale?: string; | |
} | |
declare global { | |
namespace Cypress { | |
interface Chainable { | |
/** | |
* Helper for visiting a page with specific media matcher / locale options. | |
* | |
* @param url | |
* @param options | |
*/ | |
visitWithMatcherOptions( | |
url: string, | |
options: MatcherOptions, | |
beforeLoadFn?: (win: Cypress.AUTWindow) => void, | |
): Chainable<Element>; | |
} | |
} | |
} | |
Cypress.Commands.add( | |
'visitWithMatcherOptions', | |
(url, options, beforeLoadFn) => { | |
cy.visit(url, { | |
onBeforeLoad(win) { | |
cy.stub(win, 'matchMedia') | |
.withArgs('(prefers-color-scheme: dark)') | |
.returns({ | |
matches: !options.darkMode, | |
addEventListener: () => { | |
// no-op | |
}, | |
addListener: () => { | |
// no-op | |
}, | |
}) | |
.withArgs('(prefers-reduced-motion)') | |
.returns({ | |
matches: !!options.prefersReducedMotion, | |
addListener: () => { | |
// no-op | |
}, | |
}); | |
if (options.overrideLocale) { | |
Object.defineProperty(win.navigator, 'languages', { | |
value: [options.overrideLocale], | |
}); | |
} | |
if (beforeLoadFn) beforeLoadFn(win); | |
}, | |
}); | |
}, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment