2

Is it possible to get any css value out of the DOM element being tested using Jest, Enzyme, Chai, etc.? From what I have seen so far, you can only get those css values that are mentioned in the code as style objects. But I'm not finding a way to get any other css value that the element can have in DOM. For example, if in the code using style object you provide an element a width of 50%, in unit testing its not possible to get the actual pixel value of that percentage width value. Or if you have not even mentioned width, height, etc., can you extract the derived css values that the element receives after being mounted in the DOM?

My assumption is, because unit testing happens in a node environment simulating a DOM-like environment but not an actual browser, its not possible to get the actual DOM values in some cases.

Rahul Dole
  • 2,723
  • 2
  • 24
  • 30
  • 2
    Mocha / Chai / jasmine etc don't have access to the DOM as they don't run in the browser. You can use packages like Karma to run your tests in the browser where you will have full DOM access, or jsdom which mocks a lot of browser variables. As a note you can use karma with any testing framework, it just executed them in the browser instead of node. – David Sherman Mar 13 '18 at 07:32
  • Thanks, this makes sense. I thought Jest also uses jsdom. But maybe Karma is more suitable. – Rahul Dole Mar 13 '18 at 08:38

1 Answers1

1

You can get the DOM element if you use mount(), not with shallow():

const wrapper = mount(<MyElement />)
const domEl = wrapper.getDOMNode()

More info: https://github.com/airbnb/enzyme/blob/master/docs/api/ReactWrapper/getDOMNode.md

Miguel Calderón
  • 3,001
  • 1
  • 16
  • 18