ItzaMi
ItzaMi

Reputation: 367

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---);

Upvotes: 3

Views: 1900

Answers (1)

dex
dex

Reputation: 275

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

Upvotes: 3

Related Questions