Skip to content

getStylesheetsFromDocument crash on JSDOM: TypeError: Cannot read properties of undefined (reading 'mediaText') #3753

@AriPerkkio

Description

@AriPerkkio

Product

axe-core

Product Version

4.5.0

Latest Version

  • I have tested the issue with the latest version of the product

Issue Description

Expectation

I'm using axe-core in jsdom environment when testing UIs with jest-axe. When updating axe-core from 4.4.3 to 4.5.0 a new error started to show up in logs.

Actual

The getStylesheetsFromDocument function crashes when sheet.media.mediaText is run. The cssom package used by jsdom does not implement StyleSheet.media, NV/CSSOM#1.

/**
* Get stylesheets from `document`
* -> filter out stylesheet that are `media=print`
*
* @param {Object} rootNode `document`
* @returns {Array<Object>}
*/
function getStylesheetsFromDocument(rootNode) {
return Array.from(rootNode.styleSheets).filter(sheet =>
filterMediaIsPrint(sheet.media.mediaText)
);
}

How to Reproduce

Here is really minimal reproduction case with getStylesheetsFromDocument copied from axe-core to demonstrate the issue:

const JSDOM = require("jsdom").JSDOM;

const dom = new JSDOM(`
    <!DOCTYPE html>
    <head>
        <style>
            @media (max-width: 1px) { a { color: red; } }
        </style>
    </head>
    <body>
        <p>Hello world</p>
    </body>
`);

function getStylesheetsFromDocument(rootNode) {
    return Array.from(rootNode.styleSheets).filter(function (sheet) {
        return filterMediaIsPrint(sheet.media.mediaText);
    });
}

function filterMediaIsPrint() {}

getStylesheetsFromDocument(dom.window.document);
// ^^ Uncaught TypeError: Cannot read properties of undefined (reading 'mediaText')

Additional context

cssom is unmaintained and the linked issue is 12 years old. I know adding such work-arounds in axe-core's sources is not ideal, but as everything has been working nicely for many years, I hope this small fix could be applied.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ungroomedTicket needs a maintainer to prioritize and label

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions