mardi 23 juin 2020

Testing the pseudo-element of a referenced styled component

I have a toggle switch where my styled input component references my styled label component

const Knob = styled.span`
  position: absolute;
  top: 0;
  left: 0;
  width: 3.25rem;
  height: 2rem;
  border-radius: 15px;
  background: ${basic[600]};
  cursor: pointer;
  &::after {
    content: "";
    display: block;
    border-radius: 50%;
    width: 1.7rem;
    height: 1.7rem;
    margin: 3px;
    background: #ffffff;
    transition: 0.2s;
  }
`;

const Toggle = styled.label`
  position: relative;
  ${applyStyleModifiers(BUTTON_MODIFIERS_STATUS)};
`;

const Check = styled.input`
  opacity: 0;
  z-index: 1;
  &:checked + ${Knob} {
    background: ${primary[500]};
    &::after {
      content: "";
      display: block;
      border-radius: 50%;
      width: 1.7rem;
      height: 1.7rem;
      margin-left: 1.3125rem;
      transition: 0.2s;
    }
  }
`;

When the Check component is checked the Knob component has some of its styles updated. I want to test the styles of the pseudo-element before and after the checkbox is clicked.

I am able to successfully test styles before

    const { getByTestId } = render(<ToggleSwitch ariaLabel="primary" />);
    const toggle = getByTestId("toggle-switch");
    const checkbox = getByTestId("toggle-checkbox");
    expect(toggle).toHaveStyleRule("border-radius", "50%", {
      modifier: "&::after",
    });

After I click the checkbox I am still able to test the background of the Knob component using toHaveStyle rather than toHaveStyleRule as this is not part of the pseudo-element :after.

   expect(checkbox.checked).toEqual(false);
    fireEvent.click(checkbox);
    expect(checkbox.checked).toEqual(true);

    expect(toggle).toHaveStyle(`background : ${primary[500]}`);

However I am not able to test any of the changes on the pseudo-element.

    expect(toggle).toHaveStyleRule("margin", "1.3125rem", {
      modifier: "&::after",
    });

The above does not work and tells me that the expected margin is still 3px. What I believe I need to do is use toHaveStyle and attach the &::after modifier, but I have had no success with this yet.

When I try

expect(toggle).toHaveStyle(`margin : 1.3125`, { modifier: "&::after" });

My test always passes regardless of the margin value entered.

Aucun commentaire:

Enregistrer un commentaire