score:10

Accepted answer

TLDR; You will not be able to test media-queries with current setup (jest-dom).

After debugging and going through github repository of jest-dom, it seems it will be pretty hard to test what responsive design.

There are couple of issue with the way, jest-dom (which uses jsdom) library renders component and calculates style.

To begin with, it doesn't attach/compute styles from attached stylesheet. This came with surprise to me as I am used to test UI with Angular setup. As mentioned in the attached link, you can try to overcome this issue by manually creating style element

const style = document.createElement('style')
style.innerHTML = `
  @media screen and (min-width: 500px) {
    .title .adjectives {
      display: none;
      color: red;
    }
  }
`;
document.body.appendChild(style)

or use helper function to do that as suggested in this bug.

After this change, I assumed it would work but to my surprise, it FAILED!, I checked with non-media query style and it was attaching style perfectly and that's when I discovered this TODO comment in jsdom, which makes sense as media-query styles are not working.

To conclude, it will not be possible to test media-query at the moment with react-testing-library. I haven't checked if it is working with enzyme setup, but it might who knows!

on you can use end to end testing framework such as Cypress.


Related Query

More Query from same tag