如何修复背景颜色单元测试

Nal*_*hin 5 unit-testing reactjs jestjs react-testing-library

我正在为带有情感样式的组件编写单元测试。

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

我已经编写了这个测试,但它从未通过。

  it('Should change the background color', () => {
    const color = 'rgb(140, 52, 30)';

    const { container } = render(<SelectedColor color={color} />);

    expect(container).toHaveStyle(`background: ${color}`);
  });

Run Code Online (Sandbox Code Playgroud)

Ale*_*ada 4

根据文档,容器是在 a 中呈现的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}`); 
Run Code Online (Sandbox Code Playgroud)