我正在为一个带有情感样式的组件编写单元测试。
import React from 'react';
import PropTypes from 'prop-types';
import styled from '@emotion/styled';
const Selected = styled.div`
width: 40%;
height: auto;
background: ${props => props.color};
`;
const SelectedColor = ({ color }) => {
return <Selected color={color} />;
};
我写了这个测试,但它从未通过。 it('Should change the background color', () => {
const color = 'rgb(140, 52, 30)';
const { container } = render(<SelectedColor color={color} />);
expect(container).toHaveStyle(`background: ${color}`);
});
最佳答案
根据文档,容器在 div
中呈现,所以你需要检查 container.firstChild
在这种情况下。
https://testing-library.com/docs/react-testing-library/api#container-1
这就是测试的最终结果:
const color = 'rgb(140, 52, 30)';
const { container } = render(<SelectedColor color={color} />);
expect(container.firstChild).toHaveStyle(`background: ${color}`);
关于reactjs - 如何修复背景颜色单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57485417/