css-modules / css-modules-require-hook

A require hook to compile CSS Modules in runtime

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`css-modules-require-hook` and `jest`

rodoabad opened this issue · comments

#I have this setup in my jest config.

    moduleNameMapper: {
        '^.+\\.(scss)$': '<rootDir>/test/utils/css-hooks.js'
    },
const hook = require('css-modules-require-hook');
const sass = require('node-sass');

hook({
    extensions: [
        '.scss'
    ],
    preprocessCss: (data, file) => {
        return sass.renderSync({ // eslint-disable-line no-sync
            data,
            file
        }).css;
    }
});

When I use mocha this resolves to _styles_header__styles which is something I can test against.

// mocha.opts
--require ./test/utils/css-hooks.js

However, in jest this returns undefined.

There is a good solution for jest in official docs: http://facebook.github.io/jest/docs/en/webpack.html#mocking-css-modules

It replaces all the css files with Proxy object, so you'll be able to access all the keys without any computations.

{
  "jest": {
    "moduleNameMapper": {
      "\\.scss$": "identity-obj-proxy"
    }
  }
}

This is only a solution in that it allows tests not to fail.
Some people (like myself) actually want to write tests based on the computed css-modules class names.

Using this actually changes the behaviour of a React component where className is based on props, className will be undefined when mocking CSS, but not when actually importing the CSS.

I have been trying to find a solution to this that actually imports the CSS via CSS Modules. I have a documentation generation script that uses css-modules-require-hook and it works perfectly. Importing and hooking css-modules-require-hook in jest/setup.js or through jest.config.js has not been possible so far.

Hi,

I've been using babel-plugin-css-modules-transform to apply the same transform for both build and unit test steps.
Might be a solution.

Hi there, any progress with that?