Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imported styles object is empty in Jest

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.

like image 232
Frozen Crayon Avatar asked Nov 14 '17 18:11

Frozen Crayon


1 Answers

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.

like image 152
Martin Shishkov Avatar answered Sep 23 '22 19:09

Martin Shishkov