Imported styles object is empty in Jest

笑着哭i 提交于 2019-12-22 05:55:25

问题


I have a component:

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

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

This is the test case:

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

console.log(wrapper.debug()); gives

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

instead of

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

If I console the imported styles I get

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

This is only in Jest test cases. Style is not undefined when the app renders in browser.

My jest config:

{
  "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"
  }
}

Using jest v21.2.1, identity-obj-proxy v3.0.0 and React v16.0.0.


回答1:


You have to change this line

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

to this:

import styles from './RedComponent.css';

I assume that you are using css-loader or similar and this is just how the loader works.




回答2:


Maybe worths to check the example: https://github.com/keyanzhang/jest-css-modules-example/

I think your moduleNameMapper should be like this:

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



来源:https://stackoverflow.com/questions/47292537/imported-styles-object-is-empty-in-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!