reactjs - 如何使用 jest 和 React-testing-library 测试来自 sass 的样式?

标签 reactjs sass jestjs react-testing-library

我需要从 sass 测试组件的样式,但 dom 中仅加载内联样式

我的测试用例:

   describe('Danger', () => {
      const dangerLabel = <DangerLabel>TESTE</DangerLabel>;
      it('deve ter class -danger', () => {
        const { container } = render(dangerLabel);
        expect(container.firstChild).toHaveClass('-danger');
      });
      it('deve ter a cor vermelho', () => {
        const { container } = render(dangerLabel);
        const style = window.getComputedStyle(container.firstElementChild);
        expect(style.backgroundColor).toBe('#e74c3c');
      });
    });

Jest 配置

module.exports = {
  roots: ['<rootDir>'],
  transform: {
    '\\.(js|jsx)?$': 'babel-jest',
  },
  testMatch: [
    '<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}',
  ],
  moduleFileExtensions: ['js', 'jsx', 'json', 'node'],
  testPathIgnorePatterns: ['/node_modules/', '/public/'],
  setupFilesAfterEnv: [
    '@testing-library/jest-dom/extend-expect',
  ],
  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/config/jest/__mocks__/fileMock.js',
    '.+\\.(css|scss)$': 'identity-obj-proxy',
  },
};

组件导出:

 import LabelContainer from './label_container';
    import Label from './DefaultLabel';
    import DangerLabel from './DangerLabel';
    import PrimaryLabel from './PrimaryLabel';
    import WarningLabel from './WarningLabel';
    import SuccessLabel from './SuccessLabel';
    import InfoLabel from './InfoLabel';
    import '../assets/styles/label.scss';
    
    export default Label;
    export {
      LabelContainer,
      PrimaryLabel,
      DangerLabel,
      WarningLabel,
      SuccessLabel,
      InfoLabel,
    };

执行:

expect(received).toBe(expected) // Object.is equality

    Expected: "#e74c3c"
    Received: ""

      30 |       const { container } = render(dangerLabel);
      31 |       const style = window.getComputedStyle(container.firstElementChild);
    > 32 |       expect(style.backgroundColor).toBe('#e74c3c');
         |                                     ^
      33 |     });
      34 |   });
      35 |

我尝试过一些软件包,例如 jest-transform-css 和 jest-transform-scss 但没有成功,可以进行该测试吗?

按要求 危险标签代码:

import React from 'react';
import DefaultLabel from './DefaultLabel';

const DangerLabel = props => (
  <DefaultLabel {...props} className="-danger" />
);

export default DangerLabel;

默认标签 enter image description here

使用 toHaveStyle:

 it('deve ter a cor vermelho', () => {
      const { container } = render(dangerLabel);
      expect(container.firstElementChild).toHaveStyle(`
        background-color: rgb(231, 76, 60)};
      `);
    });

结果:

enter image description here

最佳答案

在测试文件中渲染 DangerLabel 时,您缺少 visible 属性,这就是它未渲染并导致测试 #1 失败的原因。

const dangerLabel = <DangerLabel visible>TESTE</DangerLabel>;

您将面临的下一个错误是从 window.getCompulatedStyle 获取的 style 对象中的所有 CSS 属性均为空字符串(在测试 #2 中) )。有一个reason到它。

因此,我继续使用 toHaveStyle 断言背景颜色 CSS 属性的替代实现。来自 jest-dom 库。本身。

我必须使用 npm 模块 hex-rgb用于将十六进制颜色转换为 rgba 值。

查看正在运行的解决方案 here 。要在codesandbox中查看测试结果,请阅读this

奖励:使用 style 对象不起作用,但有一种声明性方式可以从 getCompulatedStyle 的返回值访问 CSS 属性 - const backgroundColor = style 。 getPropertyValue('背景颜色).

关于reactjs - 如何使用 jest 和 React-testing-library 测试来自 sass 的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68852580/

相关文章:

带阴影的css空心圆

css - 更改输入自动完成框的颜色

javascript - 用 Jest 模拟 ES6 类函数

javascript - 在 React 中加载外部 JSON

javascript - 当 prop 在父组件中更改时,子组件中的输入不会更新

angular - 使用 SCSS 时如何防止 Angular@12 在 <link> 标签上渲染 'onload' 属性

javascript - 开 Jest : resolves return undefined from Promise

typescript - 使用 Typescript 从 Jest 手动模拟导入函数

javascript - componentDidMount 内的 "setState(…): Can only update a mounted or mounting component"

javascript - 在 Axios 请求上使用 Lodash 的 Debounce 会产生意外结果