如何在 testing-library-react 中得到结果 'toHaveStyle'?

How to get the result 'toHaveStyle' in testing-library-react?

测试库 react 没有捕捉到 'toHaveStyle'。
当我单击 'Content' 时,其具有 blue 颜色的子项已更改为 red 颜色。

然而,在我的测试中,它们始终具有 blue 颜色。

我应该怎么做才能解决这个问题?

[...]
<Content data-testid={"list-element-content"} id={data.id} toggle={state[data.id - 1]}>
  <div>{data.titleUnBold}</div>
  <BoldTitle>{data.titleBold}</BoldTitle>
</Content>
[...]

const Content = styled.div`
  color: ${ (props) => props.toggle ? "red" : "blue" };
`;

下面的测试代码:

test("color changed", () => {
  const mockState = [false];
  const mockSwitchGuide = jest.fn();
  const { getAllByTestId, rerender } = render(
    <GuideListPresenter
      data={mockListData}
      state={mockState} 
      onClick={mockSwitchGuide}
    />
  );

  act(() => {
    fireEvent.change(getAllByTestId("list-element-content")[0],{
      target: {toggle: true},
    });
  });

  rerender(
    <GuideListPresenter data={mockListData} state={mockState} onClick={mockSwitchGuide} />
  );
  expect(getAllByTestId("list-element-content")[0].toggle).toEqual(true);  // success 
  expect(getAllByTestId("list-element-content")[0]).toHaveStyle("color: red");   // failed
})

要测试组件的样式,您可以直接从 html 文档中获取它,并准确查看特定元素使用的样式。

在您的示例中,您将执行如下操作:

it('should change color to red on toggle click', () => {
  const { container, getAllByTestId } = render(
    <GuideListPresenter
      data={mockListData}
      state={mockState} 
      onClick={mockSwitchGuide}
    />
  );

  // Replace <YOUR_DIV_ID> by your component's id
  let contentDiv = document.getElementById('<YOUR_DIV_ID>');
  let style = window.getComputedStyle(contentDiv[0]);
  expect(style.color).toBe('blue'); // Sometimes, only rgb style type is read here. See the rgb that corresponds to your color if need be.

  act(() => {
    fireEvent.change(getAllByTestId("list-element-content")[0],{
      target: {toggle: true},
    });
  });

  // Get the updated contentDiv
  contentDiv = document.getElementsByClassName('<YOUR_DIV_CLASS_NAME>');
  style = window.getComputedStyle(contentDiv[0]);
  expect(style.color).toBe('red');

  expect(getAllByTestId("list-element-content")[0].toggle).toEqual(true);
}

在这里,为了获取元素的样式,我使用了元素的 id。但是,它也可以与元素的 className 一起使用,并改为使用方法 document.getElementByClassName('YOUR_DIV_CLASS_NAME')。请注意,这里的给定名称应该是唯一的,可以使用 id 技术,也可以使用 className.