Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create wrapper matcher around .toHaveStyleRule #407

Open
rnarcos opened this issue Apr 5, 2022 · 0 comments
Open

Create wrapper matcher around .toHaveStyleRule #407

rnarcos opened this issue Apr 5, 2022 · 0 comments

Comments

@rnarcos
Copy link

rnarcos commented Apr 5, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant