【问题标题】:Imported styles object is empty in Jest导入的样式对象在 Jest 中为空
【发布时间】:2018-04-27 19:12:27
【问题描述】:

我有一个组件:

import React from 'react';
import * as styles from './RedComponent.css';

class RedComponent extends React.Component {
  render () {
    return <div className={ styles.red }></div>;
  }
}

这是测试用例:

describe('Test suite', () => {
  test('RedComponent tests', () => {
    const wrapper = shallow(<RedComponent />);
});

console.log(wrapper.debug()); 给了

<div className={[undefined]}></div> 

而不是

<div className="RedComponent__red"></div>

如果我控制导入的样式,我会得到 ​​p>

console.log(styles); // {default: {}}

这仅在 Jest 测试用例中。应用在浏览器中呈现时样式未定义。

我的笑话配置:

{
  "moduleFileExtensions": [
    "js"
  ],
  "moduleDirectories": [
    "node_modules"
  ],
  "moduleNameMapper": {
    "\\.(css|less)$": "identity-obj-proxy"
  },
  "setupFiles": [
    "./test-setup.js"
  ],
  "collectCoverageFrom": [
    "src/**/*.{js}",
    "!**/node_modules/**"
  ],
  "testEnvironment": "node",
  "transform": {
    "^.+\\.js$": "babel-jest",
    "\\.(md|ttf|txt|eot|ico|otf|svg|png|gif|woff2|woff|jpeg)$": "./file-transformer.js"
  }
}

使用 jest v21.2.1、identity-obj-proxy v3.0.0 和 React v16.0.0。

【问题讨论】:

  • 试试这个import styles from './RedComponent.css';
  • @MartinShishkov 哇,好用!您可以将此作为答案发布吗?你也知道为什么import * as 不起作用吗?

标签: css reactjs jestjs css-modules


【解决方案1】:

也许值得检查示例: https://github.com/keyanzhang/jest-css-modules-example/

我觉得你的moduleNameMapper应该是这样的:

"^.+\\.(css|less)$": "identity-obj-proxy"

【讨论】:

  • 糟糕,我将通过 props 传递的类名误认为是从导入的样式应用的类名,并认为这可行,但它不起作用。
【解决方案2】:

你必须改变这一行

import * as styles from './RedComponent.css';

到这里:

import styles from './RedComponent.css';

我假设您使用的是css-loader 或类似的,这就是加载程序的工作方式。

【讨论】:

  • 确实如此。为了启用 CSS 模块,您必须将 webpack 配置为使用 css-loader 以及将选项 modules 设置为 true
【解决方案3】:

创建一个jest/identity-obj-proxy-esm.js 文件,内容如下:

// This works around the fact we use ES named exports for styles, e.g.:
// import * as styles from './styles.scss'.
// https://github.com/keyanzhang/identity-obj-proxy/issues/8
module.exports = new Proxy(
  {},
  {
    get: function getter(target, key) {
      if (key === '__esModule') {
        // True instead of false to pretend we're an ES module.
        return true;
      }
      return key;
    },
  },
);

编辑jest.config.js:

// jest.config.js

module.exports = {
  ...
  moduleNameMapper: {
    ...
    '\\.(css|scss)$': '<rootDir>/jest/identity-obj-proxy-esm.js',
  }
};

? 若昂·维埃拉和https://github.com/keyz/identity-obj-proxy/issues/8#issuecomment-430241345

【讨论】:

    猜你喜欢
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    相关资源
    最近更新 更多