Cypress Component Runner - Dark Mode

Viewed 106

I am using Cypress 10 and use the interface a lot when building my components, but find the light theme harsh on my eyes, is there a dark mode available?

1 Answers

enter image description here

TLDR

Copy and paste the below code in cypress/support/component.ts.

//cypress/support/component.ts
import { mount } from 'cypress/react'
import './commands'
declare global {
    namespace Cypress {
        interface Chainable {
            mount: typeof mount
        }
    }
}
Cypress.Commands.add('mount', (jsx, options) => {
    assertDarkThemeAttached()
    const result = mount(jsx, options)
    result.then(() => parent.window.document.querySelector('iframe')!.style.display = '')
    return result
})

const assertDarkThemeAttached = () => {
    const parentHead = Cypress.$(parent.window.document.head)
    if (parentHead.find('#cypress-dark').length > 0)
        return
    parentHead.append(`<style type="text/css" id="cypress-dark">\n${style}</style>`)
    parent.window.eval(`
    const observer = new MutationObserver(() => {
        const iframe = document.querySelector('iframe')
        if(!iframe) return;
        const cyRoot = iframe.contentDocument.body.querySelector('[data-cy-root]')
        if(!cyRoot) iframe.style.display = 'none'
        // iframe.style.display = cyRoot ? '' : 'none'
    })
    observer.observe(document.body, { attributes: true, childList: true, subtree: true })
    `)
}
//wrapper for syntax highlighting
const css = (val: any) => val
const style = css`

@media (prefers-color-scheme: dark) {

    :root {
        --active-color: #cccccc;
        --background: #222426;
    }
    html, body, #spec-filter, .h-full, .flex, .spec-container, .bg-white{
    background-color: var(--background) !important;
    color: var(--active-color) !important;
    }
}
`

How it works

  • Cypress.Commands.add(...
    • Override the mount function to make sure the dark theme is attached and then mount. Note it will only 'go dark' once the first test is mounted.
  • @media (prefers-color-scheme: dark)...
    • Match your os theme, Comment out the block to have it on all the time.
  • parent.window.eval(...
    • Disable the iframe while the test is loading or we'll get a horrible white flash. It is enabled again on mount.
  • Notes:
    • I've only tested this on the Chrome Component test runner
    • this doesn't effect the tests themselves, thats up to you to make dark mode for your site :)

Extra Credit - Dark Chrome Theme

Before installing a new theme the cypress one must be deleted, otherwise it will revert any changes made the next time the browser is opened.

  1. Delete the theme folder from the cache, ie C:\Users\USERNAME\AppData\Local\Cypress\Cache\CYPRESS_VERSION\Cypress\resources\app\packages\extension
  2. Open Cypress Chrome
  3. Install a dark theme, ie just black
Related