styled-components / jest-styled-components

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

Create wrapper matcher around .toHaveStyleRule #407

Open rnarcos opened 2 years ago

rnarcos commented 2 years ago

Hi 👋

I maintain a small library that allows specific customizations to styled-components.

I found that testing those styles is becoming too repetitive since on every test file I have to repeat the same testing logic, which is basically:

  1. Receiving a component;
  2. Receiving the customizations;
  3. Test if the appropriate CSS property matches the customization value;

My current idea is to create a jest matcher, something along the lines of .toHaveCustomization in order to test all the customizations.

Just to illustrate, my customizations look something along the lines of:

interface StyleCustomization {
  marginTop: string;
}

interface WithStyleCustomization {
  styleCustomization: StyleCustomization;
}

function customizationStyle<Props extends WithStyleCustomization>(
  props: Props
) {
  const { styleCustomization } = props;
  const { marginTop } = styleCustomization;

  return css`
    margin-top: ${marginTop};
  `;
}

The problem is, that I would really like to be able to use the .toHaveStyleRule as a way to extend this test, so that my matcher could look something like this:

import { datatype } from 'faker';
import { StyleCustomization } from 'somewhere';
import toHaveStyleRule from 'jest-styled-components/toHaveStyleRule?';

function toHaveCustomization(element, customization: StyleCustomization, options) {
  return toHaveStyleRule(element, 'margin-bottom', customization.marginBottom, options);
}

NOTE: Obviously my use case is way more complex than this one that I illustrated, I have multiple styles to check for customization, and I'd implement my own logic for determining if the customization have been applied or not. But I'd still count on the styling base logic already implemented on toHaveStyleRule to help me make those assertions.

I'm wondering if this is a good practice in tests (using external matches) and if this is something that could be possible in a future version. I'm more than happy to open a PR for this, exporting the toHaveStyleRule method.