【问题标题】:How can I test styles coming from sass with jest and react-testing-library?如何使用 jest 和 react-testing-library 测试来自 sass 的样式?
【发布时间】:2021-10-21 10:36:06
【问题描述】:

我需要从 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');
      });
    });

笑话配置

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;

默认标签

使用 toHaveStyle:

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

结果:

【问题讨论】:

  • 能否在说明中也包含DangerLabel 的代码?
  • 确定@ypahalajani,完成
  • 图片中的代码和你添加的代码不一样

标签: reactjs sass jestjs react-testing-library


【解决方案1】:

在测试文件中渲染 DangerLabel 时,您丢失了 visible 属性,这就是它没有渲染并且测试 #1 失败的原因。

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

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

所以,我继续使用 jest-dom 库中的 toHaveStyle 断言背景颜色 CSS 属性的替代实现。自己。

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

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

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

【讨论】:

  • 感谢您的代码框示例,关于可见的对不起,它在默认道具中配置为 true。我已经尝试过,就像你对 toHaveStyle 所做的那样,并将颜色设置为 rgb 仍然无法正常工作,我将在描述中添加额外的更改
  • 你检查过codesandbox链接中的测试文件了吗?测试用例正在那里通过。使用您正在使用的语法检查测试文件。此外,分别使用您面临和使用的 toHaveStyle 粘贴错误和代码。
  • 我把最后的代码和结果放在描述中,我看到了codesandbox但我不明白。我输入的任何十六进制颜色,返回成功,并且css文件不包含任何标签背景样式,我的情况也是使用scss可能有一些区别
  • 好的,您能在密码箱中复制您的行为并在此处发送链接,以便我更好地帮助您吗?
  • 知道了!这是因为我们使用的@testing-library/jest-dom npm 包的版本不同。看到它here
猜你喜欢
  • 2021-02-11
  • 2020-03-22
  • 2021-02-28
  • 1970-01-01
  • 1970-01-01
  • 2020-05-14
  • 2020-03-24
  • 2020-01-20
  • 1970-01-01
相关资源
最近更新 更多