dev*_*ner 9 reactjs jestjs react-testing-library
测试库反应未捕获“toHaveStyle”。
当我单击“内容”时,其具有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" };
`;
Run Code Online (Sandbox Code Playgroud)
测试代码如下:
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
})
Run Code Online (Sandbox Code Playgroud)
要测试组件的样式,您可以直接从 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);
}
Run Code Online (Sandbox Code Playgroud)
在这里,为了获取元素的样式,我使用元素的id. 但是,它也可以与元素的 , 一起使用className,并使用该方法document.getElementByClassName('YOUR_DIV_CLASS_NAME')。请注意,此处的给定名称应该是唯一的,无论是使用id技术还是className.
| 归档时间: |
|
| 查看次数: |
23953 次 |
| 最近记录: |