styled-components / jest-styled-components

🔧 💅 Jest utilities for Styled Components
MIT License
1.58k stars 144 forks source link

TypeError: document.querySelectorAll is not a function #444

Closed homemade-ramen closed 5 months ago

homemade-ramen commented 5 months ago

Hi,

I'm experiencing a problem when modifying the document property with Object.defineProperty in my test code. Specifically, the isServer() function is incorrectly evaluated as false when document changes, causing document.querySelectorAll to be executed within resetStyleSheet(), resulting in a TypeError indicating that document.querySelectorAll is not a function.

Here's the relevant code:

// my test code
Object.defineProperty(window, 'document', { value.
  value: // some value here
});

// jest-styled-components/src/utils.js
const isServer = () => typeof document === 'undefined';

const resetStyleSheet = () => {
  if (!isServer()) {
    const scStyles = document.querySelectorAll('style[data-styled-version]')
    // Other code...
  }
};

This problem seems to be caused by Object.defineProperty not adding all the properties that the actual document object has in the browser environment.

I've implemented a workaround by checking if document.querySelectorAll is a function before executing it:

const resetStyleSheet = () => {
  if (!isServer() && typeof document.querySelectorAll === 'function') {
    const scStyles = document.querySelectorAll('style[data-styled-version]')
    // Other code...
  }
};

While this works, I'm curious if there is a more optimal solution. Any suggestions are welcome.