Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest | Mocking a JavaScript created & injected stylesheet

I've successfully created and injected my stylesheet using JavaScript and I have no issues with the functionality but my tests are now not passing because I get this error TypeError: Cannot set property 'parentStyleSheet' of undefined .

When I run my tests and console.log(stylesheet), indeed it returns as null.

I can't even get into the first line of my tests because I get this error thrown at me right at the start. If I comment out my insertRule(), the tests pass.

How can I mock this stylesheet so I can have my tests passing once again?

My function to create a stylesheet:

const createStyleSheet = () => {
  this.createdStyleSheet = (function () {
    const style = document.createElement('style');
    style.title = 'carousel';
    style.appendChild(document.createTextNode(''));
    document.head.appendChild(style);
    return style.sheet;
  }());
};

createStyleSheet();

this.createdStyleSheet.insertRule(---stuff inside here---);
like image 348
ItzaMi Avatar asked Dec 18 '25 21:12

ItzaMi


1 Answers

I did this to mock insertRule. If you just want to stop it from failing due to undefined this will work. If you actually need the styles added for future tests then you may need to modify this. I only returned 0 to stop my typescript from complaining

window.CSSStyleSheet.prototype.insertRule = function (rule, index) {
    const styleElement = document.createElement("style");
    const textNode = document.createTextNode(rule);
    styleElement.appendChild(textNode);
    document.head.appendChild(styleElement);
    return 0;
};

Use this link to see where you need to place your mock function
https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom

like image 180
dex Avatar answered Dec 20 '25 13:12

dex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!