【问题标题】:Why Enzyme not load style from React component?为什么 Enzyme 不从 React 组件加载样式?
【发布时间】:2021-01-11 09:21:48
【问题描述】:

我试图用 Jest 和 Enzyme 测试我的组件样式。我使用 TailwindCSS 作为我的 CSS 框架和非弹出的 create-react-app。所以这是我的组件:

import React from 'react'
import './tailwind.css' // the tailwind css

export function Alert({ children, className, icon, ...resProps }) {
  return (
    <div data-testid="qa-alert" className="my-2 p-3 text-lg bg-red-200 rounded-md flex items-center justify-center} {...resProps}>
      {icon && React.createElement(icon, { className: 'mr-2 text-xl' })}
      {children}
    </div>
  );
}

我想通过 getComputedStyle 方法测试背景颜色是否为红色(bg-red-200 或#fed7d7),这是我的测试:

it('Should have red background color', () => {
      const wrapper = mount(<Alert />);
      const alert = wrapper.find('div');
      const style = getComputedStyle(alert.getDOMNode());
      console.log(style);

      expect(style.backgroundColor).toBe('#fed7d7');
    });

但测试失败,因为我没有得到背景样式。接收到的值为空字符串。而style的日志是

CSSStyleDeclaration {
      '0': 'display',
      _values: { display: 'block' },
      _importants: { display: '' },
      _length: 1,
      _onChange: [Function]
    }

我怎样才能得到样式?

【问题讨论】:

    标签: reactjs jestjs create-react-app enzyme tailwind-css


    【解决方案1】:

    你可以通过更新存档:

    • 选择器wrapper.find('div') 过于通用。使用wrapper.find('div[data-testid="qa-alert"]') 或wrapper.find({'data-testid': "qa-alert"]})
    • 使用Enzyme hasClass进行测试

    例子:

           it('Should have red background color', () => {
            const wrapper = mount(<Alert />);
            const alert = wrapper.find({'data-testid': "qa-alert"]});
            expect(alert.hasClass('bg-red-200')).toEqual(true);
           });
    

    【讨论】:

    • 我不需要类名。我需要计算样式
    • 我明白了。 CSS 测试不是最佳实践。为了更好地进行测试,您应该尝试通过快照和可视化测试进行测试
    【解决方案2】:

    你可以尝试使用jest-dom方法toHaveStyle():

    expect(alert).toHaveStyle({backgroundColor: '#fed7d7'});
    

    【讨论】:

      猜你喜欢
      • 2018-12-16
      • 1970-01-01
      • 2017-11-17
      • 2017-07-08
      • 2020-10-20
      • 2022-06-24
      • 1970-01-01
      • 2020-09-24
      • 1970-01-01
      相关资源
      最近更新 更多