测试引用的样式组件的伪元素

tda*_*mon 8 javascript testing jestjs styled-components

我有一个切换开关,其中我的样式输入组件引用我的样式标签组件

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;
    }
  }
`;
Run Code Online (Sandbox Code Playgroud)

Check组件被选中时Knob,组件的一些样式会被更新。我想在单击复选框之前和之后测试伪元素的样式。

我之前能够成功测试样式

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

单击该复选框后,我仍然可以Knob使用toHaveStyle而不是测试组件的背景toHaveStyleRule,因为这不是伪元素的一部分:after

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

    expect(toggle).toHaveStyle(`background : ${primary[500]}`);
Run Code Online (Sandbox Code Playgroud)

但是我无法测试伪元素的任何更改。

    expect(toggle).toHaveStyleRule("margin", "1.3125rem", {
      modifier: "&::after",
    });
Run Code Online (Sandbox Code Playgroud)

上面的代码不起作用并告诉我预期margin仍然是 3px。我相信我需要做的是使用toHaveStyle并附加&::after修改器,但我还没有成功。

当我尝试时

expect(toggle).toHaveStyle(`margin : 1.3125rem`, { modifier: "&::after" });
Run Code Online (Sandbox Code Playgroud)

我的测试失败,并且在此组件上找不到指示的余量。