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

标签 reactjs unit-testing 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} />;
};
我写了这个测试,但它从未通过。
  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/

相关文章:

node.js - 使用 TFS 2015 运行 Jest 单元测试

javascript - 期望在箭头函数的末尾返回一个值 array-callback-return on filter function

javascript - import() 相当于 import { some } from 'somewhere' ;

android - 对 Android Eclipse JUnit 项目中的各个类运行 vanilla JUnit 测试

c# - 如何为没有输入和输出的方法编写单元测试?

javascript - 在 jest(NodeJs) 中编写测试来验证对象属性

javascript - 为子组件的每个实例传递两个不同的数据列表?

javascript - ReactJs 调色板抽屉

unit-testing - 单元测试覆盖率未显示在 Sonarqube 上 - 通过 Jenkins Sonar 插件运行 - 测试成功显示正确

node.js - NodeJS axios 请求自签名在浏览器中有效,但在 Jest super 测试案例中无效